ImageIO.read() works on FileInputStream, not HttpInputStream - java

I need to get a BufferedImage from an InputStream.
Currently, I can do this by running:
BufferedImage bufferedImage = ImageIO.read(inputStream);
When inputStream is an instance of FileInputStream.
However, when inputStream is an instance of HttpInputStream, the BufferedImage is null.
How can I create a BufferedImage from an HttpInputStream?
Thanks for all help!

As you are trying to read an image from URL, you can use IOUtils to read the file in byte array and then pass ByteArrayInputStream to ImageIO, e.g.:
byte[] byteArray = IOUtils.toByteArray(new URL("<url>").openStream());
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(byteArray));
openStream returns an inputstream and hence, you should be able to create bufferedImage object.

Related

Saving Image Data in a "PNG" File in 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);

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

Byte[] to BufferedImage in java

I have a problem with showing a picture from the database, the database saves the picture in blob, when i pick up the data the blob passes to Byte[], so after that i do that to show the image, why didnt work?
Select_1 xp = new Select_1();
byte[] img=xp.Select_1(username);
InputStream in = new ByteArrayInputStream(img);
BufferedImage image = ImageIO.read(in);
BufferedImage resizedImage=resize(image,204,204);
ImageIcon icon=new ImageIcon(resizedImage);
lblavatar.setIcon(icon);
Edit according to the comment:
Originally, the image was written using the following methods:
blob = (Blob) connect.createBlob();
ImageIcon ii = new ImageIcon(ficheiro);
ObjectOutputStream oos;
oos = new ObjectOutputStream(blob.setBinaryStream(1));
oos.writeObject(ii);
oos.close();
psInsert.setBlob(4, blob);
You are not serialzing a BufferedImage, but an ImageIcon.
In order to create an image from the blob data, you have to do "the opposite" of what you have been doing to create the blob. In this case, you'll have to do something along the lines of
byte[] img=xp.Select_1(username);
InputStream in = new ByteArrayInputStream(img);
ObjectInputStream ois = new ObjectInputStream(in);
ImageIcon imageIcon = (ImageIcon)ois.readObject();
Now, you have an ImageIcon, from which you can obtain the Image. For many cases, this image can be used directly. If you really need a BufferedImage, then you can do
BufferedImage bi = new BufferedImage(204,204,BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(imageIcon.getImage(), 0, 0, 204, 204, null);
g.dispose();
Then the buffered image will contain your image (already scaled to the desired target size of 204,204 in this case).
In any case, you should consider to not store the image as a serialized ImageIcon. Instead, you should write your image into a byte array as a PNG or JPG file, and store the resulting byte array as the blob in the database, as, for example, shown in Java: BufferedImage to byte array and back

Java error creating BufferedImage from ByteArrayInputStream

I'm trying to create a BufferedImage from a ByteArrayInputStream with:
byte[] imageData = getData(imageFile); // returns file as byte[]
InputStream inputStream = new ByteArrayInputStream(imageData);
String format = getFormatName(inputStream);
BufferedImage img = ImageIO.read(inputStream);
But img is always null. The input stream is valid (since I use it before to get the image format).
What could be making ImageIO return null? Do I need to use flush or close in any place?
Your call to getFormatName consumes the inputStream, so the stream pointer is at the end of the byte array. Any try to read from that stream will tell that it's at the end of the 'file'. You need to reset the stream (or create a new one) before you hand it over to the ImageIO.read() method:
String format = getFormatName(new ByteArrayInputStream(imageData));
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));

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