How to convert BufferedImage to byte[] in Java
Often times, you need to convert BufferedImage to byte array in order to store the image into database , or some other purpose. Some conversion is required as follow :
BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mypic.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
Example
This class will load an image from “c:\\image\\mypic.jpg”, use ImageIO.write to write the BufferedImage into ByteArrayOutputStream object and convert it to byte array.
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageTest {
public static void main(String [] args){
try{
BufferedImage originalImage =
ImageIO.read(new File("c:\\image\\mypic.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
分享到:
相关推荐
var img = canvas2image.convertToImage(canvas, {type: 'png'}); document.body.appendChild(img); ``` 在后台生成二维码,例如Java环境,我们可以使用`com.google.zxing`库。首先,你需要在项目中引入该库,然后...
BufferedImage image = page.convertToImage(); ImageIO.write(image, "jpg", new File("img" + File.separator + (i + 1) + ".jpg")); System.out.println("image in the page -->" + (i + 1)); } } catch ...
public ResponseEntity< byte[] > convertPdfToImage(@RequestParam("file") MultipartFile file) { // 1. 读取PDF文件 // 2. 使用icepdf进行转换 // 3. 将结果保存为字节数组 // 4. 返回字节数组作为HTTP响应 }...
BufferedImage image = WmfToImageConverter.convert(wmfBytes); // 使用第三方库进行转换 ImageIO.write(image, "PNG", new File("output.png")); // 保存为PNG ``` 然后,将图片的HTML代码插入到HTML文档中。 ...
二维码的编码模式主要分为数字(Numeric)、字母数字(Alphanumeric)和字节(Byte)三种。本示例代码中使用的是字节模式: ```java qrcode.setQrcodeEncodeMode('B'); // 'B' 表示字节模式 ``` #### 2. 二维码...