转换图片为base64

既然有了解析base64图片,那么就一定会有将图片编码格式成base64,其中解码base64用BASE64Decoder,而编码base64用BASE64Encoder,

上代码:

 //图片转化成base64字符串
	   
	    public  void GetImageStr()
	    {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
	        String imgFile = "d://aaaa.jpg";//待处理的图片
	        InputStream in = null;
	        byte[] data = null;
	        //读取图片字节数组
	        try 
	        {
	            in = new FileInputStream(imgFile);        
	            data = new byte[in.available()];
	            in.read(data);
	            in.close();
	        } 
	        catch (IOException e) 
	        {
	            e.printStackTrace();
	        }
	        //对字节数组Base64编码
	        BASE64Encoder encoder = new BASE64Encoder();
	      //返回Base64编码过的字节数组字符串
	       // return encoder.encode(data);
	        
	        System.out.println("***将图片解析为base64***"+encoder.encode(data));
	    }

  粘贴代码即可尝试,不谢

ps:需要注意的是此时生成的base64图片数据还不能在浏览器及img标签中使用,需要在其前面加上如下字符串:  data:image/gif;base64,

我刚刚已经在实际项目中实现过了,效果非常赞

更多内容可参考:https://blog.csdn.net/bbc2005/article/details/73369893

原文地址:https://www.cnblogs.com/yinyl/p/6861584.html