1 import java.awt.image.BufferedImage; 2 import java.io.ByteArrayInputStream; 3 import java.io.ByteArrayOutputStream; 4 import java.io.File; 5 import java.io.IOException; 6 7 import javax.imageio.ImageIO; 8 9 import sun.misc.BASE64Decoder; 10 import sun.misc.BASE64Encoder; 11 12 public class TestImageBinary { 13 static BASE64Encoder encoder = new sun.misc.BASE64Encoder(); 14 static BASE64Decoder decoder = new sun.misc.BASE64Decoder(); 15 16 public static void main(String[] args) { 17 System.out.println(getImageBinary()); 18 19 base64StringToImage(getImageBinary()); 20 } 21 22 static String getImageBinary(){ 23 File f = new File("c://20090709442.jpg"); 24 BufferedImage bi; 25 try { 26 bi = ImageIO.read(f); 27 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 28 ImageIO.write(bi, "jpg", baos); 29 byte[] bytes = baos.toByteArray(); 30 31 return encoder.encodeBuffer(bytes).trim(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } 35 return null; 36 } 37 38 static void base64StringToImage(String base64String){ 39 try { 40 byte[] bytes1 = decoder.decodeBuffer(base64String); 41 42 ByteArrayInputStream bais = new ByteArrayInputStream(bytes1); 43 BufferedImage bi1 =ImageIO.read(bais); 44 File w2 = new File("c://QQ.bmp");//可以是jpg,png,gif格式 45 ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动 46 } catch (IOException e) { 47 e.printStackTrace(); 48 } 49 } 50 51 }
问题是:转换后的图片颜色不对
其他人代码:
1 package cn.com; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 9 import sun.misc.BASE64Decoder; 10 import sun.misc.BASE64Encoder; 11 12 public class Base64Test 13 { 14 public static void main(String[] args) 15 { 16 String strImg = GetImageStr(); 17 System.out.println(strImg); 18 GenerateImage(strImg); 19 } 20 //图片转化成base64字符串 21 public static String GetImageStr() 22 {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理 23 String imgFile = "d://test.jpg";//待处理的图片 24 InputStream in = null; 25 byte[] data = null; 26 //读取图片字节数组 27 try 28 { 29 in = new FileInputStream(imgFile); 30 data = new byte[in.available()]; 31 in.read(data); 32 in.close(); 33 } 34 catch (IOException e) 35 { 36 e.printStackTrace(); 37 } 38 //对字节数组Base64编码 39 BASE64Encoder encoder = new BASE64Encoder(); 40 return encoder.encode(data);//返回Base64编码过的字节数组字符串 41 } 42 43 //base64字符串转化成图片 44 public static boolean GenerateImage(String imgStr) 45 { //对字节数组字符串进行Base64解码并生成图片 46 if (imgStr == null) //图像数据为空 47 return false; 48 BASE64Decoder decoder = new BASE64Decoder(); 49 try 50 { 51 //Base64解码 52 byte[] b = decoder.decodeBuffer(imgStr); 53 for(int i=0;i<b.length;++i) 54 { 55 if(b[i]<0) 56 {//调整异常数据 57 b[i]+=256; 58 } 59 } 60 //生成jpeg图片 61 String imgFilePath = "d://222.jpg";//新生成的图片 62 OutputStream out = new FileOutputStream(imgFilePath); 63 out.write(b); 64 out.flush(); 65 out.close(); 66 return true; 67 } 68 catch (Exception e) 69 { 70 return false; 71 } 72 } 73 }
时间: 2024-10-24 15:17:48