小白学习使用,直接上代码
public class ImagesTest {
//BufferedImage转流
public ByteArrayOutputStream image2Stream(BufferedImage image) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(image, format, out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return out;
}
//BufferedImage转byte[]
public byte[] image2byte(BufferedImage image) {
ByteArrayOutputStream out = image2Stream(image);
byte[] outToByteArray = out.toByteArray();
return outToByteArray;
}
public static void main(String[] args) throws IOException {
File dir =new File("imgs");
BufferedImage image =ImageIO.read(new File(dir,"jietu.png"));
byte[] res = image2byte(image);
OutputStream out = new FileOutputStream(dir+"\\b.png");
out.write(res);
out.flush();
out.close();
}
}