Show image from Data URI scheme on Java panel - java

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) { }

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);

Base64 encoded image is different from what was saved

I use ImageIO to save Base64 image string to a file:
public static String decodeBase64AndSaveImage(String data) throws IOException, BadRequestException {
try {
if (data == null) {
return null;
}
String base64Image = data.split(",")[1];
byte[] imageBytes = DatatypeConverter.parseBase64Binary(base64Image);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
String imageId = generateRandomKey(15);
ImageIO.write(img, "png", getImageFile(imageId));
return imageId;
} catch (IllegalArgumentException e) {
throw new BadRequestException("Bad image data");
}
}
I pass the following string to this method:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAADklEQVQIW2NgQAXGZHAAGioAza6+Hk0AAAAASUVORK5CYII=
In the following test I check that the if the saved content to the file is the same as what was passed to the method:
byte[] base64ImageData = Base64.encodeBase64(FileUtils.readFileToByteArray(imageFile));
Assert.assertEquals("wrong image data stored", DUMMY_IMAGE
.split(",")[1], new String(base64ImageData,
StandardCharsets.UTF_8));
But it returns a different string:
iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAADklEQVR42mNgQAXGZHAAGioAzTktUZoAAAAASUVORK5CYII=
Why does this happen ?
Note 1
It doesn't compare data:image/png;base64, so it's not the reason that it fails.
You are base64 decoding the string, using ImageIO to create a BufferedImage, converting it back to a PNG, and re-base64 encoding this result.
byte[] imageBytes = DatatypeConverter.parseBase64Binary(base64Image);
BufferedImage img = ImageIO.read(new
ByteArrayInputStream(imageBytes));
String imageId = generateRandomKey(15);
// re-encode
ImageIO.write(img, "png", getImageFile(imageId));
This all works fine. But the image encoder is encoding the image in a slightly different way to the original. They are both though valid PNG files and both valid base64 strings.
I decoded both strings and found they produced valid PNG files which look identical, but were encoded in different ways.

Share an image using a memory stream or byte array

I have some standard code to share an image in my Android app. The image exists on the storage and I provide an URI to the image. This all works fine.
However, this requires the WRITE_EXTERNAL_STORAGE permission. Is there a way I can share an image without the need of this permission, for example, to not save the image to storage, but specifying a memory stream or byte array?
Thanks!
You can convert an image file to a byte array with the following code, which I taken from an answer to a similar question: How to convert image into byte array and byte array to base64 String in android?
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
Optional step to encode in Base64
encImage = Base64.encodeToString(b, Base64.DEFAULT);

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.

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

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.

Categories

Resources