图片和字符串相互转换

该博客演示了如何将图片转换为字符串,再从字符串还原为图片。通过读取文件,将其内容转换为字节数组,然后使用byte2hex方法生成字符串。字符串可以使用hex2byte方法转换回字节数组,再输入到输出流中,从而显示原始图片。代码中处理了异常并提供了转换方法的实现。

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

try{
		OutputStream o = response.getOutputStream();
		
		// 将图片转换成字符串
		File f = new File("f:\\Vista.png");
		FileInputStream fis = new FileInputStream( f );
		byte[] bytes = new byte[fis.available()];
		fis.read(bytes);
		fis.close();
		
		// 生成字符串
		String imgStr = byte2hex( bytes );
		System.out.println( imgStr);
		
		// 将字符串转换成二进制,用于显示图片
		// 将上面生成的图片格式字符串 imgStr,还原成图片显示
		byte[] imgByte = hex2byte( imgStr );
		InputStream in = new ByteArrayInputStream( imgByte );
		
		byte[] b = new byte[1024];
		int nRead = 0;
		while( ( nRead = in.read(b) ) != -1 ){
			o.write( b, 0, nRead );
		}
		o.flush();
		o.close();
		in.close();
		
		
	}catch(Exception e){
		e.printStackTrace();
	}finally{
	}

public static String byte2hex(byte[] b) // 二进制转字符串
{
   StringBuffer sb = new StringBuffer();
   String stmp = "";
   for (int n = 0; 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值