How to convert ImageInputStream to BufferedImage in Java? - 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")));
}

Related

Trying to read image blob from oracle DB with ImageIO.read in Java not working [duplicate]

This question already has answers here:
Can't read and write a TIFF image file using Java ImageIO standard library
(5 answers)
Closed 4 years ago.
I have some images stored in an oracle DB as blobs. I want to read them and display in a JLabel. After reading them, I have tried using ImageIO.read but it always returns null. See my code below:
Blob blob = rs.getBlob(2);
BufferedImage frontImg = ImageIO.read(blob.getBinaryStream());
lblFrontImage.setIcon(new ImageIcon(frontImg));
I am able to save the image to a file however using the following code so I know the image is valid:
Blob blob = rs.getBlob(2);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream("test.jpg");
byte[] buff = new byte[4096];
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
out.close();
Other ways I have tried to display the image in a JLabel
byte[] frontBytes = rs.getBytes(2);
BufferedImage frontImg = ImageIO.read(new
ByteArrayInputStream(fileContent));
lblFrontImage.setIcon(new ImageIcon(frontImg));
And
byte[] frontBytes = rs.getBytes(2);
BufferedImage image;
ByteArrayInputStream bis = new ByteArrayInputStream(frontBytes);
image = ImageIO.read(bis);
bis.close();
lblFrontImage.setIcon(new ImageIcon(image));
Also
InputStream in = blob.getBinaryStream();
image = ImageIO.read(in);
byte[] frontImgBytes = blob.getBytes(1, (int) blob.length());
System.out.println("front bytes length: ====\n" + frontImgBytes.length);
BufferedImage frontImage = ImageIO.read(new
ByteArrayInputStream(frontImgBytes));
lblFrontImage.setIcon(new ImageIcon(frontImage));
Tried a lot of ways, just keep getting java.lang.NullPointerException. No other exception or error. Any help will be greatly appreciated.
I finally realised it was because the images were TIFF images. I couldn't use the default ImageIO libraries. I noticed another StackOverflow thread here Can't read and write a TIFF image file using Java ImageIO standard library and used your twelvemonkeys libraries #haraldK and it worked fine. Thanks a lot.

Read image and send it via socket - could not open file

I am trying to write a simple server that uses sockets and reads images from disc when it receives http request from browser.
I am able to receive the request, read the image from disc and pass it to the browser (the browser then automatically downloads the image). However, when I try to open the downloaded image, it says:
Could not load image 'img.png'. Fatal error reading PNG image file: Not a PNG file
The same goes for all other types of extensions (jpg, jpeg, gif etc...)
Could you help me out and tell me what am I doing wrong? I suspect that there might be something wrong with the way I read the image or maybe some encoding has to be specified?
Reading the image from disc:
// read image and serve it back to the browser
public byte[] readImage(String path) {
File file = new File(FILE_PATH + path);
try {
BufferedImage image = ImageIO.read(file); // try reading the image first
// get DataBufferBytes from Raster
WritableRaster raster = image.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return data.getData();
} catch (IOException ex) {
// handle exception...
}
return ("Could not read image").getBytes();
}
Writing the data via socket:
OutputStream output = clientSocket.getOutputStream();
output.write(result);
In this case, the result contains the byte array produced by the readImage method.
EDIT: second try with reading the image as normal file
FileReader reader = new FileReader(file);
char buf[] = new char[8192];
int len;
StringBuilder s = new StringBuilder();
while ((len = reader.read(buf)) >= 0) {
s.append(buf, 0, len);
byte[] byteArray = s.toString().getBytes();
}
return s.toString().getBytes();
You may use ByteArrayOutputStream, like,
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOutputStream);
and then you can write to socket as,
outputStream.write(byteArrayOutputStream.toByteArray());

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.

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.

Create image from BLOB using ImageIO?

I tried to create image from BLOB. I try following code but it is not working at step:
ImageIO.write(image, "JPG", iio);)
image is null. Please give me any suggestion.
byte[] imgData = null;
if (rs.next ())
{
Blob img = rs.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
File f1 = new File(fillFilePath); //fillFilePath = path where image want to store
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imgData));
ImageOutputStream iio = ImageIO.createImageOutputStream(f1);
ImageIO.write(image, "JPG", iio);
}
How to create image from BLOB using ImageIO?
From the JavaDoc on ImageIO.read(InputStream):
If no registered ImageReader claims to be able to read the resulting stream, null is returned.
It seems your blob doesn't represent an image format that ImageIO is able to understand. What format does the image stored in the blob have?
Below code works for me. I am able to retrieve BLOB(oracle)/binary(hive) from hive:
InputStream is=rs.getBinaryStream(1);
toImage(is,"C:\\hive_image.png");
public void toImage(InputStream is,String imagePath) throws IOException
{
BufferedImage bufferedImage=ImageIO.read(is);
ImageIO.write(bufferedImage, "png", new File(imagePath));
}

Categories

Resources