Java 将图片转二进制再将二进制转成图片
程序员文章站
2023-12-30 11:21:10
```
import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.i... ......
import java.awt.image.bufferedimage; import java.io.bytearrayinputstream; import java.io.bytearrayoutputstream; import java.io.file; import java.io.ioexception; import javax.imageio.imageio; import sun.misc.base64decoder; import sun.misc.base64encoder; public class testimagebinary { static base64encoder encoder = new sun.misc.base64encoder(); static base64decoder decoder = new sun.misc.base64decoder(); public static void main(string[] args) { system.out.println(getimagebinary()); base64stringtoimage(getimagebinary()); } static string getimagebinary(){ file f = new file("f://123456.jpg"); //这里gif动态图不可以,虽然在后面也能输出gif格式,但是却不是动图 bufferedimage bi; try { bi = imageio.read(f); bytearrayoutputstream baos = new bytearrayoutputstream(); imageio.write(bi, "jpg", baos); byte[] bytes = baos.tobytearray(); return encoder.encodebuffer(bytes).trim(); } catch (ioexception e) { e.printstacktrace(); } return null; } static void base64stringtoimage(string base64string){ try { byte[] bytes1 = decoder.decodebuffer(base64string); bytearrayinputstream bais = new bytearrayinputstream(bytes1); bufferedimage bi1 =imageio.read(bais); file w2 = new file("f://meinv.bmp");//可以是jpg,png格式 imageio.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动 } catch (ioexception e) { e.printstacktrace(); } } }