Saving Image Data in a "PNG" File in Java - java

Displaying an image in base64 is rather simple:
<img src="data:image/png;base64,hexadecimal-code-for-image-here">
However, what I'm trying to do is to convert the hexadecimal value received and the save it in a png file so I get the desired picture from the code.
For instance: let's say I have the following code:
iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABmJLR0QAAAAAAAD5
Q7t/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3wEVDTYmJtINnAAAAcRJ
REFUOMuVlL9rU1EUx7/n3psmL6VoWqoJpNgI0Vg6uXSw0E0QHBzsUJDSoSKCuLro
KIL0D3Dr2N0gOHUpdWgrLW0EW5osakNT+4Oo7+X13XuPi4L2SZ73jGf43O/hfM4l
nKnC9TtZmStfIwKFn5bXW9vvDBxKnG2YdP7BzOzDtanp+6uBGLwFx1LxF7RtHvmI
tIaUsK7AWEJW6UgbC2MYxtjQFUijky/Hy5WROQIgBbgT6nyuUBo2hvGtVf8oVPrE
GCbDwM6Hjce71WcrXUfuv1C8lC9eHiMwlCCcGgs/1CBiFEuVShhZBKcGHQ309H0e
AtAd+PXwkFa36shkPCglIaXEcOE8jABqjQMQgEhrdAIfZCNKHFmlsr3C6yuzjaCD
tr56++m9GzfvPgEDr+efPzquVZco5QkhFcJ2cxuMoGtCHfk/EPkbvxsD+dJejyIA
jMzFkYZ+v7CJ8Pt/exrbMhFoaCCNYn8G2gpy9TTm4cF+U7xZ+QIAyHKbXD2NARtv
X7w6rk8sghmtrWrN1dPErbl6qpKArp4mAl09TRzZ1dPEhK6eKuff5JenzPinp87A
JE/JFZjyznm58sSVPzz96/R+AmVHLPIJpOvnAAAAAElFTkSuQmCC
Is there any way I can convert this code to image and then store in a png file in JAVA?

Transfer the base64 into byte array and than write it to a png file.
byte[] img = Base64.getDecoder().decode(imgBase64);
Files.write(Paths.get("my.png"), img); //As suggested by Joop Eggen

Decode base64 image to byte[] then using ImageIO to write to file
byte[] imgInBytes = Base64.getDecoder().decode(base64Img);
InputStream in = new ByteArrayInputStream(imgInBytes);
BufferedImage bufferedImage = ImageIO.read(in);
File png = new File("ImageAsPNG.png");
ImageIO.write(bufferedImage, "PNG", png);

Related

Why am I getting a smaller jpg image size when converting from File->BufferedImage->byte[]

I'm testing different ways to store a jpg file in java and using a ByteArrayInputStream from a buffered image always results in a smaller file size. Is there anyway around this?
So for the whole picture, I'm currently trying to write a client-server image storing program(with eventual editing capabilities, think adobe lightroom). Uploading to the server from the client is no problem, just use Files.readAllBytes(currentFile.toPath()); and vice-versa when downloading to the client from the server, since it's being stored as a file.
The problem is what to do when I want to upload the same image I received(Assuming the image is edited and wanted to be reuploaded to server). I don't have a file created from it so I can't use the readAllBytes functions, they're only stored as an Image Object or BufferedImage. When I write that to a ByteArrayInputStream and get the size of the byte[] array to send back to the server, it's always smaller than the originals.
As a last resort I can make this into an export option so you have to download an image from the server onto the computer before editing, but it would make workflow less efficient.
currentFile = fileChooser.showOpenDialog(window);
try{
currentImage = new Image(currentFile.toURI().toString());
SelectedImageView.setImage(currentImage);
MainImageLayout.setLeft(SelectedImageView);
System.out.println("Original file length "+currentFile.length());
try {
BufferedImage bImage = ImageIO.read(currentFile);
byte[] fileContent = Files.readAllBytes(currentFile.toPath());
System.out.println("bytes from fileContent " +fileContent.length);
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", tmp);
tmp.flush();
byte[] imageBytes = tmp.toByteArray();
tmp.close();
long length = imageBytes.length;
System.out.println("length of bytearraystream " + length);
Printed Results:
Original file length 196874
bytes from fileContent 196874
length of bytearraystream 117010

Convert BufferedImage to aws...rekognition.model.Image

I'm playing around with the Amazon Rekognition. I found a really nice/easy library to take an image from my webcam which works like this:
BufferedImage bufImg = webcam.getImage();
I'm then trying to convert this BufferedImage to a com.amazonaws.services.rekognition.model.Image , which is what must be submitted to the Rekognition library. This is what I'm doing:
byte[] imgBytes = ((DataBufferByte) bufImg.getData().getDataBuffer()).getData();
ByteBuffer byteBuffer = ByteBuffer.wrap(imgBytes);
return new Image().withBytes(byteBuffer);
However when I try and do some API call to Rekognition with the Image, I get an Exception:
com.amazonaws.services.rekognition.model.InvalidImageFormatException: Invalid image encoding (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidImageFormatException; Request ID: X)
The docs state that the Java SDK will automatically base64 encode the bytes. In case, something weird was happening, I tried base64 encoding the bytes before converting:
imgBytes = Base64.getEncoder().encode(imgBytes);
However, the same Exception ensues.
Any ideas? :)
I tried encoding the image to a JPG (Rekognition supports PNG or JPG formats) and it solved the problem.
BufferedImage bufImg = webcam.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufImg, "jpg", baos);
ByteBuffer byteBuffer = ByteBuffer.wrap(baos.toByteArray());
return new Image().withBytes(byteBuffer);

Is it possible to put byte[] variable in File()?

I first parse image, and index it in database as byte[] which means the byte[] variable has that image in byte format
I am going to use images on search list.
Is it possible to put byte[] variable in File()?
ImageIO.read(new File(byteImage+".png"));
Your image is stored as a png? If so, you can ready it directly from the byte array with:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
use new FileOutputStream(fileVariable).write(bytes);

How to convert a png image to a JPG2000 format

I am capturing a person image passport using webcam lib.The genereated image is infor of png. I want to create a temporaly png file then convert that png file into JPG2000 format. How can I achieve this in java? here is my sample code n java
webcam.open();
BufferedImage image = webcam.getImage();
imagePath = "";
File temppngfile = new File(imagePath);
ImageIO.write(image, "png", temppngfile);

Getting an in-memory representation of the JPEG rendering of an Image

I need to know how to get an array of bytes from a loaded image, in java. BufferedImage seems not to supply any methods that produce an array of bytes, so what do I use?
BufferedImage bufferedImage; //assumed that you have created it already
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpg", byteStream);
byte[] byteArray = byteStream.toByteArray();

Categories