20141203 images BASE64 encoding and decoding

Source: Internet
Author: User

Recently, we need to pass the image to the mobile side by transcoding, using Base64 transcoding and decoding

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.BASE64Encoder;

Public class TEXT4 {

Public Static void Main (string[] args) {

String strimg = getimagestr();

System. out. println (STRIMG);

System. out. println (Strimg.length ());

Generateimage (STRIMG);

}

Convert images into Base64 strings

Public Static String Getimagestr () {//Converts a picture file into a byte array string and encodes it Base64

String imgfile = "c:/1.jpg";//Picture to be processed

InputStream in = null;

byte [] data = null;

Reading a picture byte array

Try {

in = new fileinputstream (imgfile);

data = new byte[in.available ()];

In.read (data);

In.close ();

} catch (IOException e) {

E.printstacktrace ();

}

BASE64 encoding of byte arrays

Base64encoder encoder = new base64encoder ();

return Encoder.encode (data);//returns BASE64 encoded byte array string

}

Base64 strings into pictures

Public Static Boolean Generateimage (String imgstr) {//Base64 decoding a byte array string and generating a picture

if (Imgstr = = null)//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 exception data

B[i] + = 256;

}

}

Create a jpeg picture

String Imgfilepath = "c:/userimg/xgk2059/111.jpg";//newly generated picture

OutputStream out = new fileoutputstream (Imgfilepath);

System. out. println ("==============================");

Out.write (b);

Out.flush ();

Out.close ();

return true;

} catch (Exception e) {

return false;

}

}

}

20141203 images BASE64 encoding and decoding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.