JAVA 将图片转换为Base64编码

这里使用的jar包是commons-codec-1.10.jar;

示例代码

 1 import java.io.FileInputStream;
 2 import java.io.FileOutputStream;
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6
 7 import org.apache.commons.codec.binary.Base64;
 8
 9
10 /**
11  * 将图片转换为Base64<br>
12  * 将base64编码字符串解码成img图片
13  * @创建时间 2015-06-01 15:50
14  *
15  */
16 public class Img2Base64Util {
17
18     public static void main(String[] args) {
19         String imgFile = "d:\\3.jpg";//待处理的图片
20         String imgbese=getImgStr(imgFile);
21         System.out.println(imgbese.length());
22         System.out.println(imgbese);
23         String imgFilePath = "d:\\332.jpg";//新生成的图片
24         generateImage(imgbese,imgFilePath);
25     }
26     /**
27      * 将图片转换成Base64编码
28      * @param imgFile 待处理图片
29      * @return
30      */
31     public static String getImgStr(String imgFile){
32         //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
33
34
35         InputStream in = null;
36         byte[] data = null;
37         //读取图片字节数组
38         try
39         {
40             in = new FileInputStream(imgFile);
41             data = new byte[in.available()];
42             in.read(data);
43             in.close();
44         }
45         catch (IOException e)
46         {
47             e.printStackTrace();
48         }
49         return new String(Base64.encodeBase64(data));
50     }
51
52     /**
53      * 对字节数组字符串进行Base64解码并生成图片
54      * @param imgStr 图片数据
55      * @param imgFilePath 保存图片全路径地址
56      * @return
57      */
58     public static boolean generateImage(String imgStr,String imgFilePath){
59         //
60         if (imgStr == null) //图像数据为空
61             return false;
62
63         try
64         {
65             //Base64解码
66             byte[] b = Base64.decodeBase64(imgStr);
67             for(int i=0;i<b.length;++i)
68             {
69                 if(b[i]<0)
70                 {//调整异常数据
71                     b[i]+=256;
72                 }
73             }
74             //生成jpeg图片
75
76             OutputStream out = new FileOutputStream(imgFilePath);
77             out.write(b);
78             out.flush();
79             out.close();
80             return true;
81         }
82         catch (Exception e)
83         {
84             return false;
85         }
86     }
87 }

附上在html中显示图片的示例;

转换后的图片base64编码字符串为/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUD......

先给转换后的字符串加入头文件<img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUD......">;

<img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAArAGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD7y+b3/MUfN7/mK6b/AIQ1v7hr5l/4KwftfeLP+Cc/7Mv/AAn3h74bS+N4J52sJr+e8MOn+Hp32rbS3UaL5ssMjllwj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Epx7JH2GTw5cFSj2ijA+yr6CuR8d/s7eAvin448N+JvE/gvwt4i8ReDZJJdB1LU9LhurrRncqWa3kdS0TEohypBBUEYIr0X+z4f7h/76NH9nQ/3D/wB9GvKjhZp3TSPAjgakXeLS+8yXgDuWYlmJ6k5NDQiRgzFmI7k5Nap02E9UP/fRpf7Oh/uH/vo0nhJeQnl8vIyPsq9cCj7KvoK1/wCz4f7h/wC+jR/Z8P8AcP8A30aPqcvIP7Pl5f18jI+yr6Cj7KvoK1/7Ph/uH/vo0f2fD/cP/fRo+py8g/s+Xl/XyOd17wtpvinTHsdU0+x1OxlZGkt7uBZ4XKOHQlHBBKuqsDjhlBHIFWjbLwSBk/rWx/Z0P9w/99Gk/s2A/wAB/wC+jR9Ula2gf2fPbQyltlXkAAn04pPsyqBwOK1/7Ph/uH/vo0f2dD/cP/fRo+py8gWXS8v6+RqeC0CaQwAwPMP8hRVjw9CtvYsqDC7yeufSivew8eWnGPkfU4SHJRjHsj//2Q==
">

时间: 2024-10-07 00:04:46

JAVA 将图片转换为Base64编码的相关文章

C#中图片转换为Base64编码,Base64编码转换为图片

#region 图片转为base64编码的字符串 public string ImgToBase64String(string Imagefilename) { try { Bitmap bmp = new Bitmap(Imagefilename); MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Lengt

python 将图片转换为base64编码转储进数据库

# _*_ coding: utf-8 _*_#中间件:拓展工具遍历文件夹,对文件夹图片进行base64编码,写入数据库,并且读取查找方法__author__ = 'wf15038'__date__ = "2018/8/28 18:38" import pymysqlimport sysfrom datetime import datetimeimport base64import os now = datetime.now().strftime('%Y-%m-%d %H:%M:%S'

将图片转换为Base64编码的字符串

图片以文件的形式存在,可以在表单中使用. 也可以转换成Base64编码的字符串,从而在css.js中以字符串的形式使用图片.例如,在css中设置背景图片.在js中用ajax上传图片. <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width

nodejs抓取网络图片转换为base64编码的图片

抓取网络图片需要加载http模块 //假定这是index.js文件 var http = require('http'); var url = 'http://p0.meituan.net/tuanpic/3df525af5a3f7fe04077567d2a6caf794904.png';  //一张网络图片 http.get(url,function(res){ var chunks = []; //用于保存网络请求不断加载传输的缓冲数据 var size = 0; //保存缓冲数据的总长度

Javascript 将图片的绝对路径转换为base64编码

Javascript将图片的绝对路径转换为base64编码 我们可以使用canvas.toDataURL的方法将图片的绝对路径转换为base64编码:在这我们引用的是淘宝首页一张图片如下: var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg"; 我们如下编写代码: function getBase64Image(img) { var canvas = document.create

Base64编码 图片与base64编码互转

package com.education.util; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; /** * Created by jn-dinggao on 2016/2/4. */ public class Base64Util { // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 public static String GetImageStr(Stri

图片和base64编码字符串 互相转换,图片和byte数组互相转换

图片和base64编码字符串 互相转换 import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; /** * @author lishupeng * @create 2017-05-06 下午 2:56 **/ public class Base64Test { public static void main(String[] args) { String strImg = GetImageSt

java实现图片与base64字符串之间的转换

java实现图片与base64字符串之间的转换 package com.zxc.testjava.ant; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import sun.misc.BASE64Decoder; import sun.misc

python将图片进行BASE64编码

import base64 f=open(r'a:\a.jpg','rb') #二进制方式打开图文件 ls_f=base64.b64encode(f.read()) #读取文件内容,转换为base64编码 f.close() print ls_f