How do i convert a image as a string to PNG file - java

I'm using a jQuery plugin called wPaint to allow users to draw their own image. I send the resulting image as a string to the server as a string which begins with
data:image/png;base64,
I tried the two approaches below but with both the approaches i'm not able to store the image.
Approach 1
String imageData = parameterParser.getStringParameter("image", "");
byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes());
FileOutputStream fileOutputStream = new FileOutputStream("/home/arvind/Desktop/test.png");
fileOutputStream.write(imgByteArray);
fileOutputStream.close();
In this case the file is written but doesn't show the image. However, when i remove the file extension i get the string that was sent to the server (i.e. whatever is in imageData).
Approach 2
String imageData = parameterParser.getStringParameter("image", "");
byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes());
InputStream in = new ByteArrayInputStream(imgByteArray);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "png", new File("/home/arvind/Desktop/test.png"));
The BufferedImage bImageFromConvert is null so I get an exception (IllegalArgumentException) when the file is created.
The Base64 class is from the apache commons codec library and is version 1.2.
Is there something I'm doing wrong?

Initially I had sent the data to the server using the following code.
$.ajax({
url : '/campaign/holiImageUpload.action',
type : 'POST',
data : "image=" + $("#wPaint2").wPaint("image")
success :function(data){
}
});
Now i'm sending the data to the server using the following code
var imgData = $("#wPaint2").wPaint("image");
$.ajax({
url : '/campaign/holiImageUpload.action',
type : 'POST',
data : {image : imgData},
success :function(data){
}
});
In the server side this is the final code :
String imageData = parameterParser.getStringParameter("image", "");
try {
imageData = imageData.substring(22);
byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes());
InputStream in = new ByteArrayInputStream(imgByteArray);
BufferedImage bufferedImage = ImageIO.read(in);
ImageIO.write(bufferedImage, "png", new File("/home/arvind/Desktop/test.png"));
catch(Exception ex){
ex.printStrackTrace();
}

It appears that you are trying to decode data:image/png'base64 along with your Base64 encoded data? You will want to remove that from the input string before you decode the Base64 data into image bytes.
Also, you don't want to decode the string as bytes... just as a string.

Related

Base64.encodeToString() not working in Android

So i have a bitmap and now i want to convert it into an imageUri (or string),
i am using this code here but its just doesn't work instead of returning the imageUri its returning a long random text.
Here is my code :
ByteArrayOutputStream baos = new ByteArrayOutputStream();
saveBitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos);
String path = Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT);
And this is what i am getting :
Instead of Base64.DEFAULT, use Base64.NO_WRAP
String path = Base64.encodeToString(baos.toByteArray(),Base64.NO_WRAP);
try below way, should be work
byte[] data = convert image in byte.
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Base64.encodeToString() encodes the byte array in a string. This isn't your uri. Rather this is your image/bitmap in Base64. You can use suitable Base64.decode to get back the byte array.
To get uri, you can use some of the other options including
Uri.fromFile(new File("your_file_path));
try {
val imageStream: InputStream? = requireActivity().getContentResolver().openInputStream(mProfileUri)
val selectedImage = BitmapFactory.decodeStream(imageStream)
val baos = ByteArrayOutputStream()
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
val encodedString: String = Base64.encodeToString(b,Base64.DEFAULT)
Log.d("check string" ,encodedString.toString())
} catch (e: IOException) {
e.printStackTrace()
}
For kotlin use this code and this is running successfully image to base64 when upload image to server . just put image uri "imageStream" here thats it.
Sorry guys, i thought Base64.encodeToString() will return me the imagePath, but i was wrong. Anyways i got the solution,
Here is the code that i have used,
ByteArrayOutputStream baos = new ByteArrayOutputStream();
saveBitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),saveBitmap,"Title",null);

Android+Java get image from URL on server and pass as string to client: Base64 decode and encode not working

In Java server I fetch image from external service URL like:
InputStream in = new java.net.URL(imageWebServiceURL).openStream();
String resultToCleint = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(IOUtils.toByteArray(in));
Then on Android I parse it like:
byte[] imageAsBytes = Base64.decode(resultToCleint.getBytes(), Base64.DEFAULT);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
Result: Image not displayed, ain't errors/exceptions neither on server nor on client.
What is the problem here?
EDIT: On android I use class android.util.Base64
Thanks,
Use Picasso library to load image:
You just need to add 1 line of code to show the image on ImageView
//Loading image from below url into imageView
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.into(imageView);
You can learn more from here
use this to convert to base 64
public static String uploadPic(Bitmap bm) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = ""+ Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
check if image is uploaded then using volley String request object download the string response using this code convert it back.
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
As commented, let's assume base64Content is the base64 string responsed from your web service/server-side app, you can refer to the following sample code:
String base64Content = jsonObject.getString("Base64Content");
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Moreover, if your server compressed reponse data either by gzip or deflate, your client app must decompress the data first.
Hope this helps!

Saving Gravatar images to the database

I want to use Gravatar but I don't want to publish users MD5 hashes of their e-mail addresses. And there is more potential problems. So I decided to download them and store them in my database.
But I have a problem with such a simple task as my profile picture (Earlybird) looks bad after downloading:
This is the code I used.
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
final URL url = new URL("http://www.gravatar.com/avatar/" + account.getGravatarHash() + "?d=identicon");
final BufferedImage image = ImageIO.read(url);
ImageIO.write(image, "jpg", baos);
pic = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
Value in pic is then directly stored to the database. Other pictures in my database are stored fine so problem must be in these lines.
EDIT:
I just partially fix the problem by changing "jpg" for a "png" even thought Gravatar tutorial is mentioning "jpg". Also I don't want to specify image format (unless all Gravatars are png). Can I avoid that? I want just save the bytes I get.
Browsers in most cases work with raw bytes. However it is highly appreciated to send "Content-Type: image/..." header for each image.
When you save bytes in DB you also have to
either save image content type, provided by Gravatar for this image or
convert image into your default format, so you can to hardcode content type for all images from your DB
To get headers, provided by Gravatar, you can use Apache HTTP Client.
To convert image into your preferred format, you can use ImageIO.
I found one similar problem with working solution:
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){
final URL url = new URL("http://www.gravatar.com/avatar/" + account.getGravatarHash() + "?d=identicon");
InputStream inputStream = url.openStream();
byte[] buffer = new byte[1024];
int n;
while (-1 != (n = inputStream.read(buffer))) {
baos.write(buffer, 0, n);
}
inputStream.close();
pic = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
Looks like this works with png and jpg Gravatars.

Show image from Data URI scheme on Java panel

I am having trouble interpreting this question.
I receive a img in JSON formated in Base64, for web developers its only do:
"".
How I can make it in Java?
You can use apache commons-codec for converting byte array. to base64 and from base64 to byte array.
Actually, you can use guava. This artifact has base64 libraries and json.
Just add com.google.guava in your maven's project.
For creating image, you can use:
InputStream in = new ByteArrayInputStream(yourbytearray);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "jpg", new File("c:/yourimage.jpg"));
//JSON funtion
String cmd_getPhoto = so.cmd_getPhoto();
//for remove ":"data:image\/png;base64,"
String imageDataBytes = cmd_getPhoto.substring(cmd_getPhoto.indexOf(",") + 1);
//for decode
Base64 b = new Base64();
byte[] decode = b.decode(imageDataBytes.getBytes());
//create the stream
InputStream stream = new ByteArrayInputStream(decode);
try {
//set the stream for a bufferedImage and do what your will with it
BufferedImage bitmap = ImageIO.read(stream);
jLabel6.setIcon(new ImageIcon(bitmap));
} catch (IOException ex) { }

Java - GIF to base64 string

how to convert gif to base64?
here's what i try so far
public static String convertImageToBase64(String urlString, String type ){
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
URL url = new URL(urlString);
BufferedImage img = ImageIO.read( url );
ImageIO.write(img, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
code above is working, but it lost the animation
Most likely the class BufferedImage does not support images with animation. So the code opens and parses the image only to the first frame.
Instead try directly getting the bytes with URL.openStream and then just convert the downloaded bytes to base64.
Notice that this way you can't be sure that the downloaded file is actually an image since you are not opening it at all. This may or may not be needed.
You have to use
public String encodeToString(byte[] src)
of class BASE64.Encoder (from java 8)
I'm assuming what you want is a Base64 representation of the GIF file itself, not the ImageIO representation. If you have an older version of Java without built-in Base64 support, Apache Commons Codec will do the job. Read the file into a byte array using URL.openStream(), not with ImageIO, then call Base64.encodeBase64String. If you want the result URL encoded, call Base64.encodeBase64URLSafe instead.
If you actually want the ImageIO representation, then you're stuck with losing the animation.

Categories

Resources