1. 程式人生 > >圖片轉化成base64字串 && base64字串轉化成圖片

圖片轉化成base64字串 && base64字串轉化成圖片

// 圖片轉化成base64字串
	public static String GetImageStr(String imgUrl) {// 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理
		// String imgFile = "C:/Users/Star/Desktop/test.png";// 待處理的圖片
		InputStream in = null;
		byte[] data = null;
		// 讀取圖片位元組陣列
		try {
			in = new FileInputStream(imgUrl);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 對位元組陣列Base64編碼
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64編碼過的位元組陣列字串
	}
// base64字串轉化成圖片
	public static String GenerateImage(HttpServletRequest request,
			String imgStr, String relroot) { // 對位元組陣列字串進行Base64解碼並生成圖片
		if (imgStr == null) // 影象資料為空
			return null;
		String newName = StringUtil.reName("") + ".png";
		// String imgUrl =
		// "shopImages/commodity/"+UploadTools.reName("")+".png";
		String path = request.getSession().getServletContext()
				.getRealPath(relroot);
		File targetFile = new File(path, newName);
		String imagePath = relroot + "/" + newName;
		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解碼
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 調整異常資料
					b[i] += 256;
				}
			}
			// 生成jpeg圖片
			// String imgFilePath = "d:/test22.png";// 新生成的圖片
			OutputStream out = new FileOutputStream(targetFile);
			out.write(b);
			out.flush();
			out.close();
			return imagePath;
		} catch (Exception e) {
			return null;
		}
	}

需使用jdk7