`

java实现图片与base64字符串之间的转换

 
阅读更多
// 图片转化成base64字符串
	public static byte[] GetImageStr() {
		String imgFile = "E://soft//1.jpg";
		InputStream in = null;
		byte[] data = null;
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] caly = null;
		try {
			caly = Base64.encodeBase64(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return caly;
	}

	// base64字符串转化成图片
	public static boolean GenerateImage(byte[] a ) {
		if (a == null) // 图像数据为空
			return false;
		try {
			// Base64解码
			byte[] b = Base64.decodeBase64(a);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			String imgFilePath = "e://112.jpg";// 新生成的图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics