byte[] to bufferedImage conversion gives null - java

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.

Related

How to convert ImageInputStream to BufferedImage in Java?

I'm trying to retrieve a image blob from mysql database and converting it back to image file. Iterating mysql ResultSet as:
while(rs.next())
{
byte[] byteArray=rs.getBytes("image_blob");
InputStream in=new ByteArrayInputStream(byteArray);
ImageInputStream is = ImageIO.createImageInputStream(in);
BufferedImage image_Bf=ImageIO.read(is);
ImageIO.write(image_Bf, "png",new File("images/"+rs.getString("name")));
}
When I compile and run my java class it gives me error:
java.lang.IllegalArgumentException: image == null!
How can i solve this issue?
ImageIO.read(is); returns null for you. Javadoc says that means it can't locate an appropriate ImageReader, which seems to be a sign of an invalid input.
Actually, your error is in this string: rs.getBytes("name");. You are not getting image content to byteArray, but rather image name in byte form, so ImageIO.read fails.
EDIT:
If it still fails with same error, then you'll have to debug. Try outputting the byte buffer to the file directly. Do you get a valid image this way? I'm pretty sure ImageIO needs a correct image to operate on and convert to PNG.
while(rs.next())
{
byte[] byteArray=rs.getBytes("image_blob");
FileOutputStream fos = new FileOutputStream("images/"+rs.getString("name"));
fos.write(byteArray);
fos.close();
}
successfully resloved this issue.Here is correct code for retrieving images from database
while (rs.next())
{
Blob image_blob=rs.getBlob("image_100x100");
int blobLength = (int) image_blob.length();
byte[] blobAsBytes = image_blob.getBytes(1, blobLength);
InputStream in=new ByteArrayInputStream( blobAsBytes );
BufferedImage image_bf = ImageIO.read(in);
ImageIO.write(image_bf, "PNG", new File(folder_path+"/"+rs.getString("name")));
}

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

Convert OpenCV Mat object to BufferedImage

I am trying to create a helper function using OpenCV Java API that would process an input image and return the output byte array. The input image is a jpg file saved in the computer. The input and output image are displayed in the Java UI using Swing.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Load image from file
Mat rgba = Highgui.imread(filePath);
Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0);
// Convert back to byte[] and return
byte[] return_buff = new byte[(int) (rgba.total() * rgba.channels())];
rgba.get(0, 0, return_buff);
return return_buff;
When the return_buff is returned and converted to BufferedImage I get NULL back. When I comment out the Imgproc.cvtColor function, the return_buff is properly converted to a BufferedImage that I can display. It seems like the Imgproc.cvtColor is returning a Mat object that I couldn't display in Java.
Here's my code to convert from byte[] to BufferedImage:
InputStream in = new ByteArrayInputStream(inputByteArray);
BufferedImage outputImage = ImageIO.read(in);
In above code, outputImage is NULL
Does anybody have any suggestions or ideas?
ImageIO.read(...) (and the javax.imageio package in general) is for reading/writing images from/to file formats. What you have is an array containing "raw" pixels. It's impossible for ImageIO to determine file format from this byte array. Because of this, it will return null.
Instead, you should create a BufferedImage from the bytes directly. I don't know OpenCV that well, but I'm assuming that the result of Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0) will be an image in grayscale (8 bits/sample, 1 sample/pixel). This is the same format as BufferedImage.TYPE_BYTE_GRAY. If this assumption is correct, you should be able to do:
// Read image to Mat as before
Mat rgba = ...;
Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0);
// Create an empty image in matching format
BufferedImage gray = new BufferedImage(rgba.width(), rgba.height(), BufferedImage.TYPE_BYTE_GRAY);
// Get the BufferedImage's backing array and copy the pixels directly into it
byte[] data = ((DataBufferByte) gray.getRaster().getDataBuffer()).getData();
rgba.get(0, 0, data);
Doing it this way, saves you one large byte array allocation and one byte array copy as a bonus. :-)
I used this kind of code to convert Mat object to Buffered Image.
static BufferedImage Mat2BufferedImage(Mat matrix)throws Exception {
MatOfByte mob=new MatOfByte();
Imgcodecs.imencode(".jpg", matrix, mob);
byte ba[]=mob.toArray();
BufferedImage bi=ImageIO.read(new ByteArrayInputStream(ba));
return bi;
}

bytes to Image Conversion in java

I am trying to convert Image to Byte Array and save it in database. Image to Byte Conversion and bytes to Image Conversion using ImageIO Method works completely fine before saving it into database. But when i retrieve bytes from Database ImageIO returns null.
FileInputStream fis = new FileInputStream(picturePath);
BufferedImage image = ImageIO.read(new File(picturePath));
BufferedImage img = Scalr.resize(image, Scalr.Mode.FIT_EXACT, 124, 133, Scalr.OP_ANTIALIAS);
ByteArrayOutputStream ByteStream = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", ByteStream);
ByteStream.flush();
byte[] imageBytes = ByteStream.toByteArray();
ByteStream.close();
PersonImage = imageBytes;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(PersonImage);
BufferedImage ImageForBox = ImageIO.read((InputStream)byteArrayInputStream);
PersonImageBox.setIcon(new ImageIcon((Image)ImageForBox));
Above code is what I do before saving picture bytes in DB. I resize the Image then convert it into bytes and then convert other way around and show it in JLabel, it works fine. But when I retrieve bytes from database and use the same code i.e.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(PersonImage); // PersonImage are bytes from dB.
BufferedImage ImageForBox = ImageIO.read((InputStream)byteArrayInputStream);
PersonImageBox.setIcon(new ImageIcon((Image)ImageForBox));
In this case ImageIO returns null. Please help.

Java: BufferedImage to byte array and back

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.

Categories

Resources