PIL saved jpeg string cannot be read in java - java

I create a PIL image string on a python server:
frame = cv.CaptureFromCAM(0)
image = Image.fromstring('RGB', cv.GetSize(frame), frame.tostring(), 'raw', 'BGR')
buffer = cStringIO.stringIO()
image.save(buffer,'JPEG')
udptransmit(buffer.getvalue())
I have a java client trying to read the transmitted image string and reform the jpeg. This however doesn't seem to be working. I created a python client just to check, and I can reform the jpeg correctly using a call to pygame's load method.
The string being sent from python, contains characters 6:10 = JFIF, which is the correct format (also recognised by python's imghdr module.
In java, I ahve tried
simply writing the byte contents of the string received into a file and naming it with a .jpeg extension. The file isn't a valid jpeg.
Using ImageIO to read the bytes from the string. This produces a null image.
Tried to fetch ImageReaderByFormat('JPEG') and parse the bytes with this. This gives me an error stating 'Image is not a JPEG, starts with 0x...'
I really can't see why python recognises the string as a valid jpeg and java doesn't. Do the two use different jpeg decoders? Even if they do, shouldn't both either validate or reject the string?

Just found a solution to the problem
The problem was with the charset used in java while converting the string sent from my python server into bytes in java.
Here's the simple modification that was required in my java client code:
Charset charset = Charset.forName("ISO-8859-1");
Byte[] bytes: Array[Byte] = cam_data.getBytes(charset)
File f = new File("image.jpeg")
FileImageOutputStream fios = new FileImageOutputStream(f)
BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes))
ImageIO.write(bim,"jpeg",fios)
The helpful link that lead me to the answer was http://www.java-forums.org/advanced-java/50516-reading-image-files-into-strings.html

Related

Not able to read tiff file after saving it from base64 string in java

I'm not able to open tiff image file from local machine after saving it from base64 string(from eclipse)
Below is the code for the same.
Byte[] decod = Base64.decodeBase64(base64encodedstring);
FileOutputStream str = new FileOutputStream(tifffilepathtosave);
BufferedOutputStream bstr = new BufferedOutputStream(str);
bstr.write(decod);
bstr.close();
When I tried to open the file
Alert saying this is not a valid bitmap file.or its format is not currently supported
But im able to open original tiff files.
Is there any other way to save tiff images properly, or am I missing anything in above code.
PF below link to access base64 string which I'm decoding and saving as a tiff file.
https://github.com/rajinikanthd08/ProjectA/blob/main/Tiffbase64%20(1).txt
This is the link of code which I'm getting response from web service and getting base64 encoded string and trying to saving in tiff.
https://github.com/rajinikanthd08/ProjectA/blob/main/SignatureDisplay.txt

Sending Images via JSON using base64 Encoding

I am testing out if it is possible to send a JSON file with a image or two. Currently, I have the images converted into bytes and I use
Base64.encodeToString(temp_arr, Base64.NO_WRAP);
(this is Androids base64 class, and I have to use .NO_WRAP feature to make it work after reading other stack overflow pages)
to convert it to a string. At this point, I pass that string object into my JSON file (Using GSON library) and add the string go it. This data will be sent to a PHP page.
I have test converting the bytes into base64 and saving to a text file, copying that text file into my php page, running it through my php page using
base64_decode($);
and that is able to properly recreate the image just fine (sha hashes match). So now I needed to test it sending it over a network and using json. Is the only difference is that base64 string is put int other json file rather then a text file, the json is sent to php, i grab the data and decode it in PHP.
now the problem is the image is corrupt, looking at both files in a hex editor, the first 20 lines or so in the hex editor match fine, but after that it does not match. Oddly enough the very end of the files have same data except the uploaded copy has extra characters making it larger in size.
So my problem is trying to find out, can it be GSON (JSON) causing the problem or something else, and if so, what can I do about it.
Sadly, the way my work is, my boss needs the data (json with text, data and etc) to be sent at same time, to same php page with the images, this is why I am sending the images via json.
Try this work for me,convert image into base64
public static String getStringImage(Bitmap bmp)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Log.e("SignUp", "Image Decode : " + encodedImage);
String asa = encodedImage;
return encodedImage;
}
//pass bitmap image and return string of base64
I believe I found my solution, problem was the Base64.encodeToString() would encode the images bytes to characters that included "+", where on the PHP side, the data would be send except all the "+" became spaces. I just had to replace all spaces with the + and it worked.

java printstream image file

Is a printstream appropriate for sending image files through a socket? I'm currently doing a homework assignment where I have to write a web proxy from scratch using basic sockets.
When I configure firefox to use my proxy everything works fine except images don't download. If I go to an image file directly firefox comes back with the error: The image cannot be displayed because it contains errors
Here is my code for sending the response from the server back to the client (firefox):
BufferedReader serverResponse = new BufferedReader(new InputStreamReader(webServer.getInputStream()));
String responseLine;
while((responseLine = serverResponse.readLine()) != null)
{
serverOutput.println(responseLine);
}
In the code above serverOutput is a PrintStream object. I am wondering if somehow the PrintStream is corrupting the data?
No, it is never appropriate to treat bytes as text unless you know they are text.
Specifically, the InputStreamReader will try to decode your image (which can be treated as a byte array) to a String. Then your PrintStream will try to encode the String back to a byte array.
There is no guarantee that this will produce the original byte array. You might even get an exception, depending on what encoding Java decides to use, if some of the image bytes aren't valid encoded characters.

Extracting metadata from PNG image

I'm trying to extract metadata from a PNG image format. I'm using this library? http://code.google.com/p/metadata-extractor/
Even though it claims that PNG format is supported I get an error File format is not supported when I try it with a PNG image. From the source (in method readMetadata also it looks like that it doesn't support PNG format: http://code.google.com/p/metadata-extractor/source/browse/Source/com/drew/imaging/ImageMetadataReader.java?r=1aae00f3fe64388cd14401b2593b580677980884
I've also given this piece of code a try as well but it also doesn't extract the metadata on the PNG.
BTW, I'm adding metadata on PNG with imagemagick like this:
mogrify -comment "Test" Demo/myimage.png
Has anyone used this library for PNG format or are there other ways to extract metadata from PNG image?
You can try PNGJ (I'm the developer)
See eg here an example to dump all chunks.
If you want to read a particular text chunk (recall that in PNG each textual metadata has a key and a value), you could write
pngr.getMetadata().getTxtForKey("mykey")
A useful little Windows program to peek inside PNG chunk structure is TweakPNG
Update: If you want to check all textual chunks (bear in mind that there are three types with some differences, but...)
PngReader pngr = FileHelper.createPngReader(new File(file));
pngr.readSkippingAllRows();
for (PngChunk c : pngr.getChunksList().getChunks()) {
if (!ChunkHelper.isText(c)) continue;
PngChunkTextVar ct = (PngChunkTextVar) c;
String key = ct.getKey();
String val = ct.getVal();
// ...
}
Bear also in mind that textual chunks with repeated keys are allowed.

transfer jpeg from c++ to android (java)

I am struggling with the transfer of a simple jpeg file inside an ID3v2 tag from c++ over a TCP socket to java (Android). The library "taglib" offers to extract this file and I am able to save the jpeg as a new file.
The send function looks like this
char *parameter_full = new char[f3->picture().size()+2];
sprintf(parameter_full,"%s\n\0",f3->picture().data());
// send
result = send(c,parameter_full,strlen(parameter_full),0);
delete[] parameter_full;
where
f3->picture().data() returns a pointer to the internal data structure (it returns char*) and
f3->picture().size() returns the size of the array.
Then Android receives it with
String imageString = inFromServer.readLine();
byte[] imageBytes = imageString.getBytes();
Bitmap cover = BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length);
But somehow decodeByteArray always returns null. My idea is that Java doesn't receive the image correctly because imageString only consists of 4 characters...while the extracted jpeg file has a size of 12.7 KB.
But what has gone wrong?
Martin
You shouldn't use string functions on byte data because 0 values are taken as string terminators. Try looking into memcpy on the C++ side if you need to copy the char* and also the byte[] read functions for InputStream on the Java side.

Categories

Resources