I have to convert a string to an image, the string looks like this:
!?ò„ÁÁø?mDé¯ïÌA¤>VbïììîϽ^/èõz²+öó¢ílãÊ… 'í¤ÛX¹-–Û?ÆêÕ ø×vý¹ÿàû•O_ž'ãàò?Euò6Χ?ç?¼ä”vE³•}Uœl#KWwöw'Dzۈ«¸µ¶vUåŽeýGåšv€ºÇéð]Þžžg¹ÜŽ^s™æ÷òž?F“7ù1|Ìdz¡Ü½Çðåù˜®‘r-'w?•“ÚaJQc'‡ÖJÙaHƒaeËéÿ<´``?_·¤‹Êäá!xÉgóáèçÓp~;¼ûþ8?¼Žïçw“Ñd:®17¨ÊÚ¶ÒØ}c[‹1K[U-’Ç?m,¦ËÊ®m?ÁË¢–…•Å¡¬ºk¾qjUn²qÕIª¢^!?Ôo9a׬ʺèн#§Öîmƒh%‹“¿?]ÉWTý›> €ˆ
... and so on.
I converted it to a byte array and then tried to convert it to an BufferedImage but I always get a null pointer exception. I did some research and found out that the reason is, that I have no inputstreamreader registered but I have no solution. my code looks like this so far:
public static BufferedImage decodeToImage(String imageString) {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
image = ImageIO.read(new ByteArrayInputStream(imageByte));
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
If somebody could help me, I would be really glad.
Edit:
The data comes from a server its for an university project is send a command to the server and thats the answer of the server when using readline on the inputstream.
Related
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.
The Imgur API allows you to send a Base64 of an image to upload that image.
I have tested that this works when I send a Base64 that looks like this:
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAQDAwQDAwQEAwQFBAQFBgoHBgYGBg0JCggKDw0QEA8NDw4RExgUERIXEg4PFRwVFxkZGxsbEBQdHx0aHxgaGxr/2wBDAQQFBQYFBgwHBwwaEQ8RGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhr/wgARCADIAKQDASIAAhEBAxEB/8QAHAAAAQUBAQEAAAAAAAAAAAAAAgABAwQFBgcI/8QAGgEAAwEBAQEAAAAAAAAAAAAAAgMEAQUABv/aAAwDAQACEAMQAAAB3xJsmd2cDMwdZG4lK6OC1HHQKytQCJEtwESpVG0o0pZiatCTosZEs8JMwmaTpN3EpHvn5/K2zdJy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YsoVW5f7ineHgxcZEAazEKeFt4wrbFrTsP+xMdIAJ4qJMilw852PJLCsycDpnmZqrPGYlLXoISmWjugEzqtPcPYBgbAD9RcksbzLnTLTEyiqWLeeVgNOGzG4kDn6S1UNjaR1QFrYRD1xaIroLT9SxbgxO85fA3FNq6dt5BUPZGr8gADqlIvLAIWdP8A5KGYoOB3nb6gNrxph7NPtIlqcw6o7CvwgqHBSi26u09RV4sEG72vZgiDg4g+oDE4P8I/UdlZXha7dShw8hHoYwehvsl+i5uiewmvmFUSso+aIPwQtY1ahzT0dRcAZAxOiaefxHkGkvD2obL4ipoYAawRIZWC0ZghWUdZ+ec3G4iqgd1X7jcgI7AF/cF8USksDw3xHbpPer0MBLalm/WCA6hbYA7cTkMzXndGYGH2Cq+VX9orsSjK+hl+xOkWfV1El53RW+FiYFYGTtHbr8Iv5lbKA7qvAdZ6l7cyJkHkz5ItAw1WK+oOM3aPQvE2qx2rG5P/AARFrIs/MNJsZ4PMJTLxfj5iWTKuzlxrUMSsSChQDS+4FBZHvrbkfBAe8aJ0W1PcL/FjApzhTDUSlmtBi6LY2mV2TNZClYBkxYmmAEF0TTumJZueW/iVBtsi6y0wvggX7oH0A5Y5W8ZEeHUZ8MdznFoK+4/54AlqtlOdxhPWuz8QmQOBphHMf4EL3z8o7lZ4hyV9yLKD3Ig3y1b9zKVI3dER9rUPvDCJ3hBRxYU/ZGQOSVeeKaMBKb7u9cVHty1xh2VsPmUR1S36MRN2+Be0lwDkKOOyo+e4WS+JVGDwi4l0vajtP0scMxX/AHJ+3R0T/9k=
This one is really long and generated by the website http://www.base64-image.de/step-1.php
However, my application code generates a Base64 that looks like this
_9j_4AAQSkZJRgABAQEASABIAAD_2wBDAAYEBQ
It is shorter and I don't know why. Could someone please explain to me how to get the long version? Thankyou so much. Below is the code I am using to get the short version. I have obviously spent a long time Googling to figure this out and no one seems interested in this long thing.
String file1 = "C:\\Users\\J\\Desktop\\test5.jpg";
System.out.println("HERE");
FileInputStream imageInFile = new FileInputStream(file1);
byte imageData[] = new byte[(int) file1.length()];
imageInFile.read(imageData);
byte[] encodedBytes = Base64.encodeBase64(imageData);
System.out.println("encodedBytes " + new String(encodedBytes));
String convertedImageData = Base64.encodeBase64URLSafeString(imageData);
System.out.println(convertedImageData);
Below is the output of both of those:
HERE
encodedBytes /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQ==
_9j_4AAQSkZJRgABAQEASABIAAD_2wBDAAYEBQ
Thanks for reading. I have tried MANY different things and come here now to ask.
imageInFile.read(imageData);
does not read the whole file into the array.
It reads some bytes length matching its internal buffer and returns as the result the number actually read.
You need to repeat the process in a loop till read no longer returns the data.
Check the javadoc.
Try these methods:
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
public static BufferedImage base64StringToImg(final String base64String) {
try {
return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String)));
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
Taken from: Java BufferedImage to PNG format Base64 String
The years have passed...
Nowadays, I think the solution can be fount here: https://www.geeksforgeeks.org/url-encoding-decoding-using-base64-in-java/
So this worked for me:
Base64.getUrlEncoder().encodeToString(bytes);
To get the byte[] bytes (completely) filled as another topic...
I tested adding an html inline image when sending an email...
<img src="data:image/jpeg;base64,_9j_4AAQSkZ...
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.
I'm using cordova/phonegap to capture image with device (currently iphone), the capturing is working fine, I get the base64 encoded image as a string in a callback:
function handlePhotoSuccess(image){
document.getElementById("uploadItemForm:picture").src = "data:image/jpeg;base64," + image;
document.getElementById("uploadItemForm:imageBase64").value = image;
}
The imageBase64 element is a hidden h:inputText.
The image show correctly, but the saved value in the bean is not correct. It has like the image's 30% and the other part is gray.
The value in the backing bean is a String, I convert it to a byte array, then save it:
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
try {
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream is = new ByteArrayInputStream(imageByte);
temp.setContent(is); //temp will be saved to database
images.put(currentAttribute.getId(), imageByte);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe I do something wrong?
Thank you in advance!
I am trying to convert Base64 encoded string (from image) [link to convertor]. Here is how I do this: First I convert the string, which is:
String str =
/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQHBhMTEhQWFBUUGBUZGRYXFxgXGBQWFRQYGBQVFxgaISogGBomGxUXITEiJSkrLi4uFx8zODMsNygtLisBCgoKDgwMFw8PFywcFB4sLCwsNyssLDcrLCwsKzcsNzc3NzcsKywsKysrLCsrKywsNysrLCsrKyssKysrKysrK//AABEIALEBHQMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAA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VKc4wcYyj3oOSak4vlJY8JKt4yjRSm1KW/LUdK47t2Xy+psAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//2Q==
like this:
byte[] imageString = str.getBytes("UTF-8");
and then I want to save the file on machine like this:
public boolean uploadImage(byte[] imageString, String name, String extension)
{
BufferedImage image = null;
String path = EVENT_FOLDER + name + "." + extension;
try
{
image = ImageIO.read(new ByteArrayInputStream(imageString)); //null returned here
ImageIO.write(image, extension, new File(path));
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
But I am getting null on this line: image = ImageIO.read(new ByteArrayInputStream(imageString));
What did I do wrong??
What did I do wrong?
You ignored the fact that the data is Base64-encoded, not UTF-8.
To convert the string to bytes to get the original data, you need to reverse that Base64 encoding, for example using this library.
byte[] imageData = Base64.decode(str);