最近遇到一个问题,服务器接收到图片转换之后的十六进制数据,怎么还原照片?
不多说,直接上代码:
package com.mybatis.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class TestImage1 {
public static void main(String[] args) throws Exception {
/* byte[] b1 =image2Bytes("d:\\1.jpg");
// for(int i=0;i<b1.length;i++) b1[i]=Integer.toHexString(b1[i] & 0xFF)
System.out.println();
FileOutputStream fos=new FileOutputStream("d:\\image.txt");
fos.write(b1);
fos.close();*/
FileInputStream fis=new FileInputStream(new File("d:\\data.txt"));
char[] ch=new char[fis.available()];
System.out.println(fis.available());
int len=fis.available();
int j=0;
System.out.println();
for(int i=0;i<len;i++){
int temp=fis.read();
char c=(char)temp;
if(temp!=32){
ch[j++]=c;
// System.out.print(c);
}
}
System.out.println();
System.out.println(new String(ch,0,j).length());
byte[] b=hexStringToBytes(new String(ch,0,j));
buff2Image(b,"d:\\test.jpeg");
fis.close();
}
static void buff2Image(byte[] b,String tagSrc) throws Exception
{
FileOutputStream fout = new FileOutputStream(tagSrc);
//将字节写入文件
fout.write(b);
fout.close();
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
static byte[] image2Bytes(String imgSrc) throws Exception
{
FileInputStream fin = new FileInputStream(new File(imgSrc));
//可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
byte[] bytes = new byte[fin.available()];
//将文件内容写入字节数组,提供测试的case
fin.read(bytes);
fin.close();
return bytes;
}
public static String hexString2binaryString(String hexString)
{
if (hexString == null || hexString.length() % 2 != 0)
return null;
String bString = "", tmp;
for (int i = 0; i < hexString.length(); i++)
{
tmp = "0000"
+ Integer.toBinaryString(Integer.parseInt(hexString
.substring(i, i + 1), 16));
bString += tmp.substring(tmp.length() - 4);
}
return bString;
}
public static String binaryString2hexString(String bString)
{
if (bString == null || bString.equals("") || bString.length() % 8 != 0)
return null;
StringBuffer tmp = new StringBuffer();
int iTmp = 0;
for (int i = 0; i < bString.length(); i += 4)
{
iTmp = 0;
for (int j = 0; j < 4; j++)
{
iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
}
tmp.append(Integer.toHexString(iTmp));
}
return tmp.toString();
}
}