`
chenxu_8456
  • 浏览: 40688 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

Java实现图片比对(1)-MD5方式

 
阅读更多
图片对比的一个思路是将文件转换为二进制文件流,然后对图片二进制流进行MD5编码,比对图片二进制流MD5编码的结果,不过该方法的缺点当同一图片使用不同的压缩算法进行存储后会失效;
public static byte[] getTuPianBytes(String name) {
		File file = new File(name);
		byte[] tuPianBytes = new byte[(int) file.length()];
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			in.read(tuPianBytes);
			in.close();
		} catch (FileNotFoundException e) {
			tuPianLog_NotSame.log("can not find file " + name);
		} catch (IOException e) {
			tuPianLog_NotSame.log("read picture error " + name);
		}
		return tuPianBytes;
	}

	private static byte[] getTuPianFromWeb(String urlAddress) {
		URL url = null;
		HttpURLConnection conn = null;
		byte[] tuPianBytes = null;
		try {
			url = new URL(urlAddress);
			conn = (HttpURLConnection) url.openConnection();
			if (conn.getResponseCode() == 200) {
				InputStream in = conn.getInputStream();
				tuPianBytes = readStream(in);
			} else if (conn.getResponseCode() == 500) {
				throw new PictureNotFoundError("can not found #ADD# picture: "
						+ urlAddress);
			}
		} catch (IOException ioE) {
			ioE.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
			if (url != null) {
				url = null;
			}
		}
		return tuPianBytes;
	}
	
	private static byte[] readStream(InputStream in) {
		try {
			ByteArrayOutputStream outstream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length = -1;
			while ((length = in.read(buffer)) != -1) {
				outstream.write(buffer, 0, length);
			}
			outstream.close();
			in.close();
			return outstream.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static String getTuPianMD5(byte[] tuPianBytes) {
		if (tuPianBytes == null) {
			return "";
		}
		byte[] strTemp = tuPianBytes;
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(strTemp);
			byte[] md = digest.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (NoSuchAlgorithmException ignore) {
			return null;
		}
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics