Convert BufferedInputStream into image
Start by verifying that uploadedInputStream
is a valid image, prehaps by writing it out using ImageIO.write
. You can always use ImageIO.read
to read the image back in and write it back out to a ByteArrayInputStream
;)
I did a quick test using H2 database.
A few things I noted. Blob#length
returns a long
, while Blob#getBytes
expects an int
, this could mean you're truncating the byte stream.
Also, from the documentation of H2, it would seem that the Blob
contents is not kept in memory, so I use the getBinaryStream
instead.
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
public class TestImageDatbase {
private Connection con;
public static void main(String[] args) {
new TestImageDatbase();
}
public TestImageDatbase() {
try {
clearDatabase();
saveImage();
loadImage();
} catch (ClassNotFoundException | SQLException | IOException exp) {
exp.printStackTrace();
}
}
protected Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
return DriverManager.getConnection("jdbc:h2:d:\\Image", "sa", "");
}
protected void clearDatabase() throws IOException, ClassNotFoundException, SQLException {
Connection con = null;
PreparedStatement stmt = null;
try {
con = getConnection();
System.out.println("Cleaning database");
stmt = con.prepareStatement("delete from images");
int updated = stmt.executeUpdate();
System.out.println("Updated " + updated + " rows");
} finally {
try {
stmt.close();
} catch (Exception e) {
}
try {
con.close();
} catch (Exception e) {
}
}
}
protected void saveImage() throws IOException, ClassNotFoundException, SQLException {
Connection con = null;
PreparedStatement stmt = null;
ByteArrayOutputStream baos = null;
ByteArrayInputStream bais = null;
try {
baos = new ByteArrayOutputStream();
File source = new File("/path/to/file");
System.out.println("Source size = " + source.length());
BufferedImage img = ImageIO.read(source);
ImageIO.write(img, "png", baos);
baos.close();
bais = new ByteArrayInputStream(baos.toByteArray());
con = getConnection();
stmt = con.prepareStatement("insert into images (image) values (?)");
stmt.setBinaryStream(1, bais);
int updated = stmt.executeUpdate();
System.out.println("Updated " + updated + " rows");
} finally {
try {
bais.close();
} catch (Exception e) {
}
try {
baos.close();
} catch (Exception e) {
}
try {
stmt.close();
} catch (Exception e) {
}
try {
con.close();
} catch (Exception e) {
}
}
}
protected void loadImage() throws IOException, ClassNotFoundException, SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = getConnection();
stmt = con.prepareStatement("select image from images");
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("Getting blob");
Blob blob = rs.getBlob(1);
System.out.println("Reading image");
BufferedImage img = ImageIO.read(blob.getBinaryStream());
System.out.println("img = " + img);
JOptionPane.showMessageDialog(null, new JScrollPane(new JLabel(new ImageIcon(img))));
}
} finally {
try {
rs.close();
} catch (Exception e) {
}
try {
stmt.close();
} catch (Exception e) {
}
try {
con.close();
} catch (Exception e) {
}
}
}
}
How to create an image from an InputStream, resize it and save it?
I did this:
try {
InputStream is = file.getInputStream();
Image image = ImageIO.read(is);
BufferedImage bi = this.createResizedCopy(image, 180, 180, true);
ImageIO.write(bi, "jpg", new File("C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg"));
} catch (IOException e) {
System.out.println("Error");
}
BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) {
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
And I did not use the other code.
Hope helps someone!
Inputstream to BufferedImage Conversion damages the file
The reason your code isn't working is in
uploadImage = ato.filter(uploadImage, null); //uploadImage == BufferedImage
Your destination image is null.
You have to create a new BufferedImage to put the scaled version into, like this:
BufferedImage dstImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
ato.filter(uploadImage, dstImage);
Then, save the dstImage (using ImageIO.write).
Edit:
An easier way to scale down the image would be to just draw it into the dstImage at the right size:
int dstWidth = 100;
int dstHeight = 100;
InputStream imageStream = item.getInputStream();
BufferedImage srcImage = ImageIO.read(imageStream);
if (srcImage == null) { System.err.println("NO SOURCE IMAGE!"); }
BufferedImage dstImage = new BufferedImage(dstWidth, dstHeight,
BufferedImage.TYPE_INT_RGB);
dstImage.getGraphics().drawImage(
srcImage, 0, 0, dstWidth, dstHeight, null);
ImageIO.write(dstImage, "jpg", new File(path + ".jpg"));
How do I convert a InputStream to BufferedImage in Java/Groovy?
BufferedImage imBuff = ImageIO.read(object.getInputStream());
Should work...
Converting input stream into bitmap
Thank you @Amir for point out the log. Discovered a line:
decoder->decode returned false
This seems to be a common problem. Doing a search I found a solution.
My previous code:
URLConnection conn = url.openConnection();
conn.connect();
inputStream = conn.getInputStream();
bufferedInputStream = new BufferedInputStream(inputStream);
bmp = BitmapFactory.decodeStream(bufferedInputStream);
Code which is working:
HttpGet httpRequest = null;
try {
httpRequest = new HttpGet(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
bmp = BitmapFactory.decodeStream(instream);
Source
Convert image obtained from url into inputstream. Then read that inputstream to convert it into image & display on my jsp
Hope this will solve your problem.
package com.intellectdesign.cash.gdm.common;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class ImageByte {
public static void main(String args[]) throws MalformedURLException, IOException {
getImageAndTypeFromInputStream();
}
public static byte[] getImageAndTypeFromInputStream() throws MalformedURLException, IOException {
String format = null;
BufferedImage bufferedimage = null;
InputStream input = null;
URLConnection openConnection = new URL("http://www.thumbprintbooks.ca/wp-content/uploads/Vignettes-Photos-Spine-Inset-In-Plinth-thumbnail-c-Thumbprint-Books.jpg").openConnection();
openConnection.addRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
input = openConnection.getInputStream();
System.out.println("input : " + input.toString());
System.out.println("input : " + input.getClass());
System.out.println("input : " + input.available());
BufferedInputStream in=new BufferedInputStream(input);
ImageInputStream stream=ImageIO.createImageInputStream(in);
Iterator readers=ImageIO.getImageReaders(stream);
if (readers.hasNext()) {
System.out.println("if block");
ImageReader reader = (ImageReader) readers.next();
format = reader.getFormatName();
reader.setInput(stream);
bufferedimage = reader.read(0);
new BufferedImageWrapper(format, bufferedimage);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "jpg", byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
} else {
System.out.println("else block");
String text = "OOPS !!!";
byte convertEntry[] = text.getBytes();
return convertEntry;
}
}
public static class BufferedImageWrapper {
private final String imageType;
private final BufferedImage bufferedimage;
public BufferedImageWrapper(String imageType, BufferedImage bufferedimage) {
System.out.println("in Buffered image Wrapper");
this.imageType = imageType;
this.bufferedimage = bufferedimage;
}
public String getImageType() {
return imageType;
}
public BufferedImage getBufferedimage() {
return bufferedimage;
}
}
}
How to make ImageIO read from InputStream :Java
ImageIO.read()
takes InputStream
as a parameter so there is no meaning of casting it to ImageInputStream
.
Secondly you can not cast an InputStreamReader
object to ImageInputStream
because ImageInputStream
has nothing to do with InputStreamReader
which you thought of.
Moreover getResourceAsStream()
returns InputStream
. So you can directly do it like this.
InputStream resourceBuff = YourClass.class.getResourceAsStream(filepath);
BufferedImage bf = ImageIO.read(resourceBuff);
How to convert BufferedImage to InputStream?
You need to save the BufferedImage to a ByteArrayOutputStream
using the ImageIO
class, then create a ByteArrayInputStream
from toByteArray()
.
How to load streamed data directly into a BufferedImage
In order to read the image before writing it to disk, you'll need to use a ByteArrayInputStream. http://docs.oracle.com/javase/6/docs/api/java/io/ByteArrayInputStream.html
Basically, it creates a inputstream that reads from a specified byte array. So, you'd read the image length, then it's name, then the length-amount of bytes, create the ByteArrayInputStream, and pass it to ImageIO.read
Example snippet:
long fileLength = dis.readLong();
String fileName = dis.readUTF();
byte[] bytes = new byte[fileLength];
dis.readFully(bytes);
BufferedImage bimage = ImageIO.read(new ByteArrayInputStream(bytes));
Or using the code from the other answer you cited:
String dirPath = ...;
ServerSocket serverSocket = ...;
Socket socket = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = dis.readLong();
String fileName = dis.readUTF();
byte[] bytes = new byte[fileLength];
dis.readFully(bytes);
BufferedImage bimage = ImageIO.read(new ByteArrayInputStream(bytes));
//do some shit with your bufferedimage or whatever
files[i] = new File(dirPath + "/" + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bytes, 0, fileLength);
bos.close();
}
dis.close();
Related Topics
Is -Djava.Library.Path=... Equivalent to System.Setproperty("Java.Library.Path", ...)
Is There a Java Library to Access the Native Windows API
Jpa, How to Use the Same Class (Entity) to Map Different Tables
Java Error: Cannot Make a Static Reference to the Non-Static Method
How to Set Tls Version on Apache Httpclient
How to Copy the Contents of One Arraylist into Another
How to Have Case Insensitive Urls in Spring MVC with Annotated Mappings
Sslhandshakeexception: No Subject Alternative Names Present
Generate JPA 2 Entities from Existing Database
Fastest Way to Iterate an Array in Java: Loop Variable VS Enhanced for Statement
How to Hide a Jframe in System Tray of Taskbar
How to Declare a 2D String Arraylist
Maximum Amount of Memory Per Java Process on Windows
What Does the 'New' Keyword Actually Do in Java, and Should I Avoid Creating New Objects