图片转byte[]
//imagefile to byte
public static byte[] image2byte(String path) throws IOException {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum = 0; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
// System.out.println("read" + readNum + "bytes,");
}
byte[] bytes = bos.toByteArray();
return bytes;
}
byte[]转图片
//byte to imagefile
public static void byte2image(byte[] bytes, String path) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
// Returns an ImageInputStream that will take its input from the given
// Object
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
// got an image file
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
image.getHeight(null), BufferedImage.TYPE_INT_RGB);
// bufferedImage is the RenderedImage to be written
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
File imageFile = new File(path);
ImageIO.write(bufferedImage, "jpg", imageFile);
// "jpg" is the format of the image
// imageFile is the file to be written to.
// System.out.println(imageFile.getPath());
}