java将十六进制字符串转换成图片

本文介绍了一种方法,用于将十六进制字符串转换为图片文件。通过解析十六进制数据并将其转换为字节数组,最终可以保存为图片格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.fset.framework.uitl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class HexToPicture {

public static void main(String[] args) throws Exception {
String str="图片的十六进制流";
String strs=str.replace(" ", "");
byte[] b=hexStringToBytes(strs);
buff2Image(b,"f:\\test.jpg");

}

 
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();  
    }  
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值