[英]Java: How To Convert Image to Byte[]
I'm having an image in Database in bytearray format. 我在数据库中使用bytearray格式的图像。 I want to display on browser. 我想在浏览器上显示。 I don't know how to write Image using OutputStream. 我不知道如何使用OutputStream编写Image。 Here is my code. 这是我的代码。
byte[] imageInBytes = (byte[]) obj; // from Database
InputStream in = new ByteArrayInputStream(imageInBytes);
Image img = ImageIO.read(in).getScaledInstance(50, -1, Image.SCALE_SMOOTH);
OutputStream o = resp.getOutputStream(); // HttpServletResponse
o.write(imgByte);
You may try something like this: 你可以尝试这样的事情:
File f=new File("image.jpg");
BufferedImage o=ImageIO.read(f);
ByteArrayOutputStream b=new ByteArrayOutputStream();
ImageIO.write(o, "jpg", b);
byte[] img=b.toByteArray();
You have to set the content type of the response to be an image type that you are sending. 您必须将响应的内容类型设置为要发送的图像类型。 Suppose your image was stored when it was a jpeg. 假设您的图像是jpeg时存储的。 then, 然后,
OutputStream o = resp.getOutputStream(); // HttpServletResponse
o.setContentType("image/jpeg");
o.write(img.getBytes() /* imgByte */);
would send the browser an image. 会向浏览器发送图像。 ( The browser understands from the header information that the following information you just sent it, is a jpeg image. ) (浏览器从标题信息中了解到您刚刚发送的以下信息是jpeg图像。)
You could try using ImageIO.write
... 您可以尝试使用ImageIO.write
...
ImageIO.write(img, "jpg", o);
But this will require you to use BufferedImage
when reading... 但这需要你在阅读时使用BufferedImage
...
BufferedImage img = ImageIO.read(in);
You could then use AffineTransform
to scale the image... 然后,您可以使用AffineTransform
缩放图像...
BufferedImage scaled = new BufferedImage(img.getWidth() / 2, img.getHeight() / 2, img.getType());
Graphics2D g2d = scaled.createGraphics();
g2d.setTransform(AffineTransform.getScaledInstance(0.5, 0.5));
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
img = scaled;
This, obviously, only scales the image by 50%, so you'll need to calculate the required scaling factor based on the original size of the image against your desired size... 显然,这只会将图像缩放50%,因此您需要根据图像的原始大小和所需大小计算所需的缩放系数...
Take a look at Java: maintaining aspect ratio of JPanel background image for some ideas on scaling images... 看一下Java:维护JPanel背景图像的纵横比,以获得有关缩放图像的一些想法......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.