C # implement mutual conversion between images and BASE64 using JAVA
Base64 encoding has many Web applications, such as URL and email. A common scenario is to convert an image to a Base64 string for storage .. Both Net and Java can implement this scenario .. Net Framework also provides a ready-made function class (System. Convert) for converting binary data to a Base64 string. To Convert an image to a Base64 string, use BinaryFormatter to serialize the image file to binary data, and then use the ToBase64String method of the Convert class. The process of converting a Base64 string to an image is the opposite: Use the FromBase64String of the Convert class to obtain the binary data of the image file, and then use the BinaryFormatter deserialization method.
////// Convert image data to a Base64 string /////////Private void ToBase64 (object sender, EventArgs e) {Image img = this. pictureBox. image; BinaryFormatter binFormatter = new BinaryFormatter (); MemoryStream memStream = new MemoryStream (); binFormatter. serialize (memStream, img); byte [] bytes = memStream. getBuffer (); string base64 = Convert. toBase64String (bytes); this. richTextBox. text = base64 ;}////// Convert a Base64 string to an image /////////Private void ToImage (object sender, EventArgs e) {string base64 = this. richTextBox. text; byte [] bytes = Convert. fromBase64String (base64); MemoryStream memStream = new MemoryStream (bytes); BinaryFormatter binFormatter = new BinaryFormatter (); Image img = (Image) binFormatter. deserialize (memStream); this. pictureBox. image = img ;}
Java: import the sun. misc. BASE64Decoder. jar package. Implementation Code:
package com.axbsec.util;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.OutputStream;import Decoder.BASE64Decoder;public class StringToImg { public static final int NUMBER=2833; public static void main(String[] args) { File fPhotos=new File("C:/Users/Desktop/photos.txt"); File fIDCards=new File("C:/Users /Desktop/idcards.txt"); BufferedReader reader=null; BufferedReader reader1=null; String[] fPhotosStr; String[] fIDCardsStr; try { reader=new BufferedReader(new FileReader(fPhotos)); reader1=new BufferedReader(new FileReader(fIDCards)); fPhotosStr = new String[NUMBER]; fIDCardsStr = new String[NUMBER]; String tempString =null; String tempString1=null; int line=0; int line1=0; while ((tempString=reader.readLine())!=null) { fPhotosStr[line]=tempString; line++; } reader.close(); while ((tempString1=reader1.readLine())!=null) { fIDCardsStr[line1]=tempString1; line1++; } reader1.close(); for(int i=0;i
By converting images from these two platforms to Base64, you can easily modify the business scenario of image storage.