Example: Java realizes the conversion between image and base64 string

  • 2020-05-26 08:30:15
  • OfStack

Without further details, I will directly post java to you to realize the conversion code between the image and base84 string. The specific code is as follows:


package cn.com; 
import <a href="http://lib.csdn.net/base/javase" class='replace_word' title="Java SE The knowledge base " target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.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.BASE64Encoder; 
public class Base64Test  
{ 
  public static void main(String[] args) 
  { 
    String strImg = GetImageStr(); 
    System.out.println(strImg); 
    GenerateImage(strImg); 
  } 
  // Convert the picture to base64 string  
  public static String GetImageStr() 
  {// Convert the image file into a byte array string and proceed with it Base64 Coding processing  
    String imgFile = "d://test.jpg";// Images to be processed  
    InputStream in = null; 
    byte[] data = null; 
    // Reads the image byte array  
    try  
    { 
      in = new FileInputStream(imgFile);     
      data = new byte[in.available()]; 
      in.read(data); 
      in.close(); 
    }  
    catch (IOException e)  
    { 
      e.printStackTrace(); 
    } 
    // Pair byte array Base64 coding  
    BASE64Encoder encoder = new BASE64Encoder(); 
    return encoder.encode(data);// return Base64 A string of encoded byte arrays  
  } 
  //base64 String to image  
  public static boolean GenerateImage(String imgStr) 
  {  // To the byte array string Base64 Decode and generate images  
    if (imgStr == null) // The image data is empty  
      return false; 
    BASE64Decoder decoder = new BASE64Decoder(); 
    try  
    { 
      //Base64 decoding  
      byte[] b = decoder.decodeBuffer(imgStr); 
      for(int i=0;i<b.length;++i) 
      { 
        if(b[i]<0) 
        {// Adjust abnormal data  
          b[i]+=256; 
        } 
      } 
      // generate jpeg The picture  
      String imgFilePath = "d://222.jpg";// New generated image  
      OutputStream out = new FileOutputStream(imgFilePath);   
      out.write(b); 
      out.flush(); 
      out.close(); 
      return true; 
    }  
    catch (Exception e)  
    { 
      return false; 
    } 
  } 
} 

Related articles: