this is my question. i opened a .jpg image and wrote its each byte in a .txt file seperated with a comma. it was success. now i want to use that txt file to rebuild the image. the img.txt looks something like
255,216,255,224,0,16,74,70,73,70,0,1,1…….
the following code created the image.jpg, with the size if the original image, but but the image is not visible. im expecting help from somebody…
#include<iostream>
#include<string>
#include<fstream>
#include<sstream>
#include<cstdlib>
using namespace std;
int main(){
char *s;
long x;
ifstream is("D:\\test\\img.txt");
is.seekg(0,ios::end);
x=is.tellg();
is.seekg(0,ios::beg);
s=new char[x];
is.read(s,x);
is.close();
stringstream str;
char a[4];
int y = 0;
for(int i=0; i<=x; i++) {
if (s[i] != ',') {
a[y] = s[i];
y = y + 1;
}
if (s[i] == ',') {
str << (unsigned char)atoi(a);
a[0] = '\0';
a[1] = '\0';
a[2] = '\0';
a[3] = '\0';
y = 0;
}
}
const char *ss=(str.str()).c_str();
ofstream ex("D:\\test\\test.txt");
ex << ss;
ofstream fileo("D:\\test\\image.jpg",ios::binary);
fileo.write(ss,(str.str()).length());
}
Your code as written worked for me with Visual Studio 10 SP1. However, there is a subtle bug depending on your STL implementation (and luck):
Your code:
Is using a temporary that has gone out of scope. What
sspoints to could well be garbage immediately (or any time in the future) after this line executes. The reason isstd::stringstream::str()returns a copy of the string, it’s safe to callstd::string::c_str()on this copy, but that pointer will not be valid once the original (temporary) goes out of scope.To fix this, make sure you copy the string out of the
stringstreamobject so that the lifetime is known, like this:To reiterate, both versions are working for me, but the version I propose is actually working by design, as opposed to luck.