Java: BufferedImage to byte array and back - java

I see that a number of people have had a similar problem, however I'm yet to try find exactly what I'm looking for.
So, I have a method which reads an input image and converts it to a byte array:
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
What I now want to do is convert it back into a BufferedImage (I have an application for which I need this functionality). Note that "test" is the byte array.
BufferedImage img = ImageIO.read(new ByteArrayInputStream(test));
File outputfile = new File("src/image.jpg");
ImageIO.write(img,"jpg",outputfile);
However, this returns the following exception:
Exception in thread "main" java.lang.IllegalArgumentException: im == null!
This is because the BufferedImage img is null. I think this has something to do with the fact that in my original conversion from BufferedImage to byte array, information is changed/lost so that the data can no longer be recognised as a jpg.
Does anyone have any suggestions on how to solve this? Would be greatly appreciated.

This is recommended to convert to a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
byte[] bytes = baos.toByteArray();

Note that calling close or flush will do nothing, you can see this for yourself by looking at their source/doc:
Closing a ByteArrayOutputStream has no effect.
The flush method of OutputStream does nothing.
Thus use something like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream(THINK_ABOUT_SIZE_HINT);
boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos);
assert foundWriter; // Not sure about this... with jpg it may work but other formats ?
byte[] bytes = baos.toByteArray();
Here are a few links concerning the size hint:
Java: Memory efficient ByteArrayOutputStream
jpg bits per pixel
Of course always read the source code and docs of the version you are using, do not rely blindly on SO answers.

Related

Save java.awt.Image to disk in java

I have read clob from oracle procedure and convert them into java.awt.Image object by the following code .
InputStream stream = clob.getAsciiStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
int a1 = stream.read();
while (a1 >= 0) {
output.write((char) a1);
a1 = stream.read();
}
Image myImage = Toolkit.getDefaultToolkit().createImage(output.toByteArray());
output.close();
Now, I want to save myImage to hard disk. So, What must I do to save these java.awt.Image to file ?
My try :
I have cast the myImage to BufferedImage and then write this to ImageIo by the following code :
BufferedImage bi = (BufferedImage)myImage;
ImageIO.write(bi, "jpg",new File("E:\\out.jpg"));
But I am getting the following exception :
Got Exception as : sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
at com.connect.home.Home.getHomeParameter(Home.java:103)
at com.connect.home.Home.main(Home.java:141)
How can I remove this error ? Any advice is of great help .
First
Oracle JDBC drivers support the manipulation of data streams in either
direction between server and client. The drivers support all stream
conversions: binary, ASCII, and Unicode. Following is a brief
description of each type of stream:
Binary. Used for RAW bytes of data, and corresponds to the getBinaryStream method
ASCII. Used for ASCII bytes in ISO-Latin-1 encoding, and corresponds to the getAsciiStream method
Unicode. Used for Unicode bytes with the UTF-16 encoding, and corresponds to the getUnicodeStream method
So probably you will need to use clob.getBinaryStream to retrieve your stream.
Second. You can not save ToolKitImage whith ImageIO::write because it expect a RenderedImage instance.And ToolkitImage not implements this interface.
So you have two options.
Read the stream with ImageIO
RenderedImage image = ImageIO.read(clob.getBinaryStream());
ImageIO.write(image, "JPG",new File("E:\\out.jpg"));
Or draw the ToolkitImage on a RenderedImage
BufferedImage bi = new BufferedImage(myImage.getWidth(null), myImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(myImage,0,0, null);
ImageIO.write(bi, "JPG", new File("E:\\out.jpg"));

Reading an image as byte array with Android: skImageDecoder::Factory returned null

I have a Spring MVC Web Service that returns an image as a byte array. The output is in json format. The format is png
Here's the code snippet for the image.
BufferedImage img = ImageIO.read(new File(caminho.replace("/", "//")));
imagem = ((DataBufferByte) img.getRaster().getDataBuffer
()).getData();
When I run the server, this is the output:
[{"id":0,"caminhoMDPI":null,"caminhoHDPI":"C:/Users/Marcos/Pictures/postos/drawable-
mdpi/esso_logo.png","caminhoXHDPI":null,"caminhoXXHDPI":null,"imagem":"AAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAA....]
Eventually, other symbols appear on the "imagem" field. I suppose this is right, but I'm not
sure.
On my Android app, I have a routine to download the image and store it as a blob in the database. I receive the json format and transform it into a class with jackson. I've logged the "imagem" field and it looks the same.
My problem is that I can't transform it into an image. Here's the code snippet:
byte[] img_bandeira = cursor.getBlob(cursor.getColumnIndex("img_bandeira"));
Bitmap bmpBandeira = BitmapFactory.decodeByteArray(img_bandeira, 0, img_bandeira.length);
ImageView ivBandeira = (ImageView) view.findViewById(R.id.ivBandeira);
ivBandeira.setImageBitmap(bmpBandeira);
All I get is a message: skImageDecoder::Factory returned null.
I've looked at other similar posts, tried to change some lines, but nothing happened. I don't know what's going on here. Thanks in advance.
I solved it. In the server, the image should be sent like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage img = ImageIO.read(new File(caminho.replace("/", "//")));
ImageIO.write(img, "png", baos);
baos.flush();
String base64String = Base64.encode(baos.toByteArray());
baos.close();
In my app, it should be read like this:
public static Bitmap getImage(byte[] imageArray) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageArray);
Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);
return bitmap;
}
Thank you, everybody ;)

Converting byte array to jpg image file throughing exception

Hi I have a byte array that I am converting to jpg image but that is giving exception as below please explain me wht is the problem with this.
ByteArrayInputStream bis = new ByteArrayInputStream(someByteArray);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
//ImageIO is a class containing static methods for locating ImageReaders
//and ImageWriters, and performing simple encoding and decoding.
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
BufferedImage image = reader.read(0, param);
//got an image file
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
//bufferedImage is the RenderedImage to be written
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
File imageFile = new File("D:\\newrose2.jpg");
ImageIO.write(bufferedImage, "jpg", imageFile);
Exception:
javax.imageio.IIOException: Invalid JPEG file structure: SOS before SOF
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:550)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:550)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(JPEGImageReader.java:295)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(JPEGImageReader.java:427)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(JPEGImageReader.java:543)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:986)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:966)
at Trnsport.writejpegfile(Trnsport.java:398)
at Trnsport.getData(Trnsport.java:107)
at Trnsport.run(Trnsport.java:63)
at java.lang.Thread.run(Thread.java:722)
Edit:
FileOutputStream fos = new FileOutputStream("image" + new Date().getTime() + ".jpg");
fos.write(someByteArray);
fos.close();
If your byte array already contains valid JPEG data, you do not need to invoke the JPEG reader or writer -- you can write the bytes to the file using ordinary file I/O.
If the byte array actually contains some format of raw pixel data, you will need to load it into a BufferedImage directly (such as via setRGB) and encode that as a JPEG.
The fact that you're getting an exception trying to decode it implies it is not JPEG data, but raw pixel data. Or, perhaps it is a different type of image altogether, or it has an image at some offset into the array instead of at the start the array, or it is not an image at all.

convert all images to PNG

I need a dynamic solution to convert a unknown image format to .png in java.
Will .getType() help me out here, it seems only to return numbers.
The converted image should later be stored in a folder, but I guess that is easly done in the
ImageIO.write().
It's just that with converting an unknown image format that I have no idea how to approach.
This peace of code should do the magic:
File file = new File("unknown.type.pic");
ByteArrayInputStream bais = new ByteArrayInputStream(FileUtils.readFileToByteArray(file);
BufferedImage image = ImageIO.read(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
OutputStream outputStream = new FileOutputStream ("output.jpg");
baos.writeTo(outputStream);
Add missing try/catch/finally blocks.

byte[] to bufferedImage conversion gives null

I am trying to convert byte[] array to buffered image so than i can resize the image..but problem is conversion always turned into null.here is my code..
ByteArrayInputStream bais = new ByteArrayInputStream(user.getUser_image());
//Here user.getUser_image() returns byte[] returned from server..
try {
BufferedImage image = ImageIO.read(bais);
System.out.println("============><================"+image);//Here it prints null
BufferedImage scaledImage = Scalr.resize(image,48);
}
.....and so on
It means that the ImageIO class is not able to select an appropriate ImageReader. The purpose of this could be corrupted byte array or unsupported image type. Try to debug it.

Categories

Resources