I'm trying to convert a matrix of (doubles) into an unsigned char so I can then write to a .pmg file... But it isn't working.
void writePNG(vector<double>& matrix)
{
vector<unsigned char> image;
ofstream myfile;
myfile.open("newFile.txt", ios::out); // writing to .txt file for now for testing.
if(!myfile.is_open())
{
cout << "Cannot open file";
}
for(int i=0; (i < 512*512); i++)
{
image[i] = (unsigned char) matrix[i];
}
myfile.close();
}
It won't convert the data. Any ideas?? Thanks :)
fstream
object goes out of scope vector::vector
displays your intent more clearly. Try this:
#include <vector>
#include <iostream>
#include <fstream>
void writePNG(const std::vector<double>& matrix)
{
std::ofstream myfile("newFile.txt", std::ios::out);
if(!myfile.is_open())
{
std::cout << "Cannot open file";
}
std::vector<unsigned char> image (matrix.begin(), matrix.end());
myfile.write(reinterpret_cast<const char*>(&image[0]), image.size());
}
int main () {
writePNG({
72, 101, 108.1, 108.2,
111, 0x2c, 0x20, 0x77,
0x6f, 0x72, 0x6c,
100.3, 10.4});
}
You are creating image
using the default constructor of vector
, which initializes the vector as empty (containing no elements). The subscript notation ( image[i]
) does not create an element, only assigns to an already exising one.
You have (at least) two ways to fix it:
image
using the ctor of vector
that allocates the necessary size: vector<unsigned char> image(512*512)
-- this will populate the vector with 512*512 elements of default value (0 for unsigned char
) push_back
method: image.push_back((unsigned char) matrix[i]);
You also will have to write the contents of image
to myfile
eventually.
Note: it is a good habit to use static_cast<unsigned char>(...)
instead of the C-style (unsigned char) ...
as the former can find errors that the latter will not flag; this is not an issue in this particular case, though
You image vector has zero size - you would have to at least do a push_back to add an element. Also, the size of a double is not the same size of a char so you are going to lose information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.