Base64编码转图片

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/thewindkee/article/details/51729161

今天在群里,有人问 富文本的图片怎么上传。




 

类似于:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACUAAAAjCAIAAACcpVRJAAAAB3RJT…eLRjPLt95OKtC53ocA6L1f5yLutp53UXU0/1eM/wtyp3n/BJW6iQ7mPHyQAAAAAElFTkSuQmCC">

 

 

       想了下, 这里的base64后面的那一串数据就是 图片被base64编码了而已。所以只需要把这串数据上传到服务器就可以。服务器接收到后,判断文件名,图片格式,图片内容是字符串。把这个字符串用base64解码成字节数组, 再用FileOutputStream输出成对应格式的图片就可以了,我这张图片是png,那么就保存成png。

           网上搜了下,有其它插件,但是应该也是这样的原理。

import java.io.FileOutputStream;
import java.io.IOException;

import com.mysql.jdbc.util.Base64Decoder;

public class Base64Test {
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws IOException {
		Base64Decoder decoder=new Base64Decoder();
                //图片被base64编码的字符串
		String s="iVBORw0KGgoAAAANSUhEUgAAACUAAAAjCAIAAACcpVRJAAAAB3RJTUUH4AUbBQc49OACfgAABSpJREFUeJztlluMlVcVx///tfd35nznnAGGGWAyQgM0JamlBoomgvGhJfrggww06QudakNIGltTq5im0qYvlQd9MUZNfPHCgMRw6YQHiYkxPhQnppQmFhPEtrS0JS3iMJyZObf97bV8+M5wKYdzxkvwxfX4rfXt37ruvVitVnEHRe4k7P+8/w3PYnZ7VeyivVV8D72qmdJ5AHb5EmambaYKU4pDuWKLB2RwOQBoBAXkf8ZThQgh8dRJeePV8OZZ+/CDAcucSFS9AoeRu/z6DfzkRvnUZwDArCeS3edPP3gnHjugpyeXis5m2orKJAEJMwuhz0nZyxS82/yg7HhMlg71jK8bL56azA7+aPHVqashwnmYwgxm878SJMUhtIre1YeGk6dfkFV3d4+yE88MZHxtMv74u4UsNCkwzb+T13AkzTB/LpnSGmnF7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u0g0kiIY5IUTMuC5j3r/bf3ceSu271Ebcd67C9Tl/X4IT31ytJ6tR6tHtVIirOYCZB6SciZRYPYtMXveAzlSs+VqStv/ufs3Bm8cdrO/SWeP8dmvV9QpZe0hJWruW69e2CzrLnnRvt/P772re8cAJup2uWPkAVr1lmqMClgYIiVfgAWM4pbyP7Zi5eLRjPLt95OKtC53ocA6L1f5yLutp53UXU0/1eM/wtyp3n/BJW6iQ7mPHyQAAAAAElFTkSuQmCC";
		byte [] b=decoder.decode(s.getBytes(), 0, s.getBytes().length);
		FileOutputStream out=new FileOutputStream("E:\\a.png");
		out.write(b);
		out.close();
	}
}


效果




展开阅读全文

没有更多推荐了,返回首页