Java pictures and byte arrays convert to each other __java

Source: Internet
Author: User
Picture to byte array
Public byte[] Image2byte (String path) {
byte[] data = null;
Fileimageinputstream input = null;
try {
input = new Fileimageinputstream (new File (path));
Bytearrayoutputstream output = new Bytearrayoutputstream ();
byte[] buf = new byte[1024];
int numbytesread = 0;
while ((Numbytesread = Input.read (BUF))!=-1) {
Output.write (buf, 0, Numbytesread);
}
data = Output.tobytearray ();
Output.close ();
Input.close ();
}
catch (FileNotFoundException Ex1) {
Ex1.printstacktrace ();
}
catch (IOException Ex1) {
Ex1.printstacktrace ();
}
return data;
}
byte array to picture
public void Byte2image (byte[] data,string path) {
if (data.length<3| | Path.equals ("")) return;
try{
Fileimageoutputstream imageoutput = new Fileimageoutputstream (new File (path));
Imageoutput.write (data, 0, data.length);
Imageoutput.close ();
System.out.println ("Make the picture success,please find image" + path);
catch (Exception ex) {
System.out.println ("Exception:" + ex);
Ex.printstacktrace ();
}
}
byte array to 16 binary string
Public String byte2string (byte[] data) {
if (data==null| | Data.length<=1) return "0x";
if (data.length>200000) return "0x";
StringBuffer sb = new StringBuffer ();
int buf[] = new Int[data.length];
Convert byte array to decimal
for (int k=0;k<data.length;k++) {
Buf[k] = data[k]<0? (data[k]+256):(data[k]);
}
Decimal converts to hexadecimal
for (int k=0;k<buf.length;k++) {
if (buf[k]<16) sb.append ("0" +integer.tohexstring (buf[k));
Else Sb.append (integer.tohexstring (buf[k));
}
Return "0x" +sb.tostring (). toUpperCase ();

}


File Resolution:
Fileimageoutputstream replaced FileOutputStream.
Fileimageinputstream replaced by FileInputStream.


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.