Save Base64 decoed image on file system - java

I am getting my image as base 64 decoded string in my spring mvc application. e.g.
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABUUAAAkFCAYAAAD3GsjUAAAgAElEQVR4nOy9eXSb932vqc50fJs2Z+6ZOefeO2dmbm/aSW9ve+MmrZv2Nmmm7TROs7q2Yzl2HNWxtmihZNmSLMd24t=
I am trying save it as a png image:
byte[] imageByte = Base64.decodeBase64(base64encodedImage);
String directory = "D:\\Image Capture\\sample.png";
FileOutputStream outputStream = new FileOutputStream(directory);
outputStream.write(imageByte);
outputStream.flush();
outputStream.close();
but it is saving my image as
I am not able to figure out the reason. This encoded image is obtained using canvas.toDataUrl in javascript. It opens in browser tab perfectly.

Finally I have figured out.
Answer on this link helped.
The encoded Image I received:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABUUAAAkFCAYAAAD3GsjUAAAgAElEQVR4nOy9eXSb932vqc50fJs2Z+6ZOefeO2dmbm/aSW9ve+MmrZv2Nmmm7TROs7q2Yzl2HNWxtmihZNmSLMd24t=
The encoded image part starts after the phrase below:
data:image/png;base64,
I had to skip that string and then decoded image.
Also I have figured out from the same thread that the extra String shouldn't stop us from decoding.
In the same forum an approach is suggested that while converting encoded image user:
InputStream stream = new ByteArrayInputStream(Base64.decode(image.getBytes(), Base64.DEFAULT));
Refer to #Wand Maker's answer in the same thread.

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.

Save byte[] to image with FileOutputStream

I send with my Android device a picture to my Java server. I do this with a byte[]. Then I want to store it at my server. But this doesn't work right. The file has the right size, but when I want to open it, windows says: The file can't be opened. What's wrong?
FileOutputStream fos = new FileOutputStream("./images/"+IDfromPost+".png");
fos.write(buffer);
fos.close();
buffer is my byte[], IDfromPost an integer.
By the way. I display the length of the byte array at my phone and the server and both are the same.
It's not a problems with Android, you have to check how you decode the byte[] in your server to convert it to a ImageFile.
If you want more help, you have to update the post with the specification of you server.
Regards.

Getting different Base64 String when trying to convert through Base64.encodeBase64URLSafeString java

I Uploaded one file Tried converting the image to Base64 String through this site http://base64.wutils.com/encoding-online/. When i am copying the base64 string from this site then it is working in my code and image is getting displayed properly
But, when i am trying to convert the image into Base64 String through Base64.encodeBase64URLSafeString the Base64 String which i am getting is not working in my code and image is not getting displayed.
Further i analysed i found out that difference between Base64 String which i copied from site and which i am generated through encodeBase64URLSafeString. Attached the snapshot for reference.Also attached the code for reference.
//this line will fetch the image data from db and i am storing into byte array
byte[] imageData = smpResource.getValue();
//i am adding this byte array into json object and sending.
JSONObject result = new JSONObject();
result.put("image", imageData);
selectedImage.innerHTML = "<img src='data:image/jpg;base64, temp'/>";
Seems like some character encoding problem.Right side of the image is working one copied from site .Can see the diff / replaced with _.How to overcome this problem.Thanks in advance

PIL saved jpeg string cannot be read in 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

Categories

Resources