图片转成16进制,16进制转图片。


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;


public class imgTransform {
	private static final Logger LOG = LogManager.getLogger(imgTransform.class);
	
	/**
	 * 图片转成十六进制
	 * 
	 */
	@Test
	public String platePhotoURL() {
		 File file = new File("C:\\Users\\zhangzq\\Desktop\\123456.jpg");
			if (file.exists()) {

				FileInputStream fs = null;
				FileChannel fc = null;
				String imge = "";
				try {
					fs = new FileInputStream(file);
					fc = fs.getChannel();
					if (fs.getChannel().size() <= 0) {
						return "";
					}
					byte[] data = new byte[(int) fc.size()];
					int reads = 0;// 循环次数
					int re = 0; // 获取值
					while ((re = (int) fs.read()) != -1) {
						data[reads] = (byte) re;
						reads++;
					}
					fs.close();
					fc.close();
					imge = bytesToHexString(data);
					return imge;
				} catch (IOException e) {
					LOG.error("图片获取失败获取失败" + e);
				}
			} else {
				LOG.info("图片不存在,上传图片失败");
			}
			return "";
		}
	
	public static String bytesToHexString(byte[] src) {

		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();

	}
	
	
	
	
	/**
     * 十六进制转成图片
     *
     */
    public static void saveToImgFile(String src,String output){
        if(src==null||src.length()==0){
            return;
        }
        try{
            FileOutputStream out = new FileOutputStream(new File(output));
            byte[] bytes = src.getBytes();
            for(int i=0;i<bytes.length;i+=2){
                out.write(charToInt(bytes[i])*16+charToInt(bytes[i+1]));
            }
            out.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    private static int charToInt(byte ch){
        int val = 0;
        if(ch>=0x30&&ch<=0x39){
            val=ch-0x30;
        }else if(ch>=0x41&&ch<=0x46){
            val=ch-0x41+10;
        }
        return val;
    }
    public static void main(String[] args)throws Exception {
        String str = "xxxx";
        saveToImgFile(str.toUpperCase(),"C:\\Users\\zhangzq\\Desktop\\test\\123.jpg");
    }

}

猜你喜欢

转载自blog.csdn.net/qq501569325/article/details/103817901
今日推荐