Base64 encoding/Decoding for image data (implemented in Java)

Source: Internet
Author: User
Package com. Vista. test;

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 mytest
{
Public static void main (string [] ARGs)
{
String strimg = getimagestr ();
Generateimage (strimg );
}
Public static string getimagestr ()
{// Convert an image file into a byte array string and encode it with base64
String imgfile = "D: // 111.jpg"; // the image to be processed.
Inputstream in = NULL;
Byte [] DATA = NULL;
// Read the image byte array
Try
{
In = new fileinputstream (imgfile );
Data = new byte [IN. Available ()];
In. Read (data );
In. Close ();
}
Catch (ioexception E)
{
E. printstacktrace ();
}
// Encode the byte array base64
Base64encoder encoder = new base64encoder ();
Return encoder. encode (data); // return a base64-encoded byte array string
}
Public static Boolean generateimage (string imgstr)
{// Decodes the byte array string using base64 and generates an image
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 a JPEG Image
String imgfilepath = "D: // 222.jpg"; // New Image
Outputstream out = new fileoutputstream (imgfilepath );
Out. Write (B );
Out. Flush ();
Out. Close ();
Return true;
}
Catch (exception E)
{
Return false;
}
}
}

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.