PDA

View Full Version : trying to read from a qfile to a unsigned short array



vmsgman
26th March 2011, 00:04
I have a binary image 1024 x 1024 or X x Y lets say, and want to save the data in a ushort array, how do I do that when all of the file.read methods use char* ?

ComaWhite
26th March 2011, 02:42
Have you looked at QDataStream? It allows like for instance



QFile file("text.txt", ...);
if (!file.open()) {
....
}

QDataStream str(&file);
qint16 val << str;
....
....
....

vmsgman
26th March 2011, 04:29
So I tried that and it seems to work, but I am getting some weird results from the function, the ushorts are 0 from index 0-1023 which is expected, 1024 = ~3000 also ok, 1025,6,7 etc, are ~45000 which is wrong, they should be ~3000 as well.

Do you see anything wrong with the code?



void MainWindow::on_actionOpen_activated()
{
QString filename = QFileDialog::getOpenFileName(
this,
tr("Open ViVA File"),
QDir::currentPath(),
tr("ViVA Image (*.viv *.raw)") );

if( !filename.isNull() )
{
qDebug( filename.toAscii() );

viv_header *hdr = new viv_header();
int32_t xDim = 0, yDim = 0;
QFile file(filename);
if (file.open(QIODevice::ReadOnly))
{
if (filename.endsWith(".viv"))
{
qint64 bytes = file.read(reinterpret_cast<char *>(hdr), sizeof(viv_header));
if (bytes != sizeof(viv_header)) {
QMessageBox::information(this, tr("ViVA Header Error"),
"The ViVA header is malformed file cannot be read!");
return;
}
xDim = hdr->ImgWidth;
yDim = hdr->ImgHeight;
}
else
{
image_size *i;
for (i = known_image_sizes; i->width != -1; i++)
{
if(i->width * i->height * sizeof(unsigned short) == file.size())
break;
}
if(i->width == -1)
{

QMessageBox::information(this, tr("File Dimension Error"),
"The file dimensions are not a recognized length!\n");
return;
}
xDim = i->width;
yDim = i->height;

if (file.pos() != 0)
file.seek(0);
}

uint64_t len = xDim * yDim;
ia = new quint16[len];

QDataStream in(&file);
for (uint64_t j = 0; j < len; j++)
in >> ia[(int)j];

file.close();
}
}
}