对网络图片进行签名,之前在与遇到

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);

启动时候有问题,后来换成了ImageIO.write(image, "jpg", out),就没有问题。

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;import javax.imageio.ImageIO;/*** 读取、输出文件* @author tyg* @date   2019年3月28日下午4:48:06*/
public class ImageHelper {// 项目根目录路径public static final String path = System.getProperty("user.dir");/*** * @param source* @param width* @param height* @param b* @return* @return BufferedImage* @author tyg* @date   2019年3月28日下午5:26:59*/public static BufferedImage thumb(BufferedImage source, int width, int height, boolean b) {// targetW,targetH分别表示目标长和宽int type = source.getType();BufferedImage target = null;double sx = (double) width / source.getWidth();double sy = (double) height / source.getHeight();if (b) {if (sx > sy) {sx = sy;width = (int) (sx * source.getWidth());} else {sy = sx;height = (int) (sy * source.getHeight());}}if (type == BufferedImage.TYPE_CUSTOM) { // handmadeColorModel cm = source.getColorModel();WritableRaster raster = cm.createCompatibleWritableRaster(width, height);boolean alphaPremultiplied = cm.isAlphaPremultiplied();target = new BufferedImage(cm, raster, alphaPremultiplied, null);} elsetarget = new BufferedImage(width, height, type);Graphics2D g = target.createGraphics();// smoother than exlax:g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));g.dispose();return target;}/*** 输出文件* @param imgPath* @param markPath* @param x* @param y* @param alpha* @return void* @author tyg* @date   2019年3月28日下午5:23:35*/public static void waterMark(String imgPath, String markPath, int x, int y, float alpha) {try {// 加载待处理图片文件Image img = ImageIO.read(new File(imgPath));BufferedImage image = new BufferedImage(img.getWidth(null), img.getHeight(null),BufferedImage.TYPE_INT_RGB);Graphics2D g = image.createGraphics();g.drawImage(img, 0, 0, null);// 加载水印图片文件Image src_biao = ImageIO.read(new File(markPath));g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));g.drawImage(src_biao, x, y, null);g.dispose();// 保存处理后的文件FileOutputStream out = new FileOutputStream(imgPath);ImageIO.write(image, "jpg", out);
//          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//          encoder.encode(image);out.close();} catch (Exception e) {e.printStackTrace();}}/*** 输出图片* @param imgPath* @param text* @param font* @param color* @param x* @param y* @param alpha* @return void* @author tyg* @date   2019年3月28日下午5:26:35*/public static void textMark(String imgPath, String text, Font font, Color color, int x, int y, float alpha) {try {Font Dfont = (font == null) ? new Font("宋体", 20, 13) : font;Image img = ImageIO.read(new File(imgPath));BufferedImage image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);Graphics2D g = image.createGraphics();g.drawImage(img, 0, 0, null);g.setColor(color);g.setFont(Dfont);g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));g.drawString(text, x, y);g.dispose();FileOutputStream out = new FileOutputStream(imgPath);ImageIO.write(image, "jpg", out);
//          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//          encoder.encode(image);out.close();} catch (Exception e) {System.out.println(e);}}/*** 读取本地JPEG、JPG图片格式* @param filename* @return* @return BufferedImage* @author tyg* @date   2019年3月28日下午5:24:36*/public static BufferedImage readJPEGImage(String filename) {try {InputStream inStream = new FileInputStream(new File(filename));BufferedImage sourceImage = ImageIO.read(inStream);
//          // 得到输入的编码器,将文件流进行jpg格式编码
//          JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(inStream);
//          // 得到编码后的图片对象
//          BufferedImage sourceImage = decoder.decodeAsBufferedImage();return sourceImage;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}/*** 读取http的JPEG、JPG图片格式* @param filename* @return* @return BufferedImage* @author tyg* @date   2019年3月28日下午5:24:26*/public static BufferedImage readHttpJPEGImage(String filename) {try {//new一个URL对象  URL url = new URL(filename);  //打开链接  HttpURLConnection conn = (HttpURLConnection)url.openConnection();  //设置请求方式为"GET"  conn.setRequestMethod("GET");  //超时响应时间为5秒  conn.setConnectTimeout(5 * 1000);  //通过输入流获取图片数据  InputStream inStream = conn.getInputStream();
//          JPEGImageDecoder imageDecoder = JPEGCodec.createJPEGDecoder(inStream);
//          BufferedImage sourceImage = imageDecoder.decodeAsBufferedImage();BufferedImage sourceImage = ImageIO.read(inStream);// 得到编码后的图片对象return sourceImage;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}/*** 读取本地PNG图片格式* @param filename* @return* @return BufferedImage* @author tyg* @date   2019年3月28日下午5:25:24*/public static BufferedImage readPNGImage(String filename) {try {File inputFile = new File(filename);FileInputStream input = new FileInputStream(inputFile);BufferedImage sourceImage = ImageIO.read(input);return sourceImage;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}public static int rgbToGray(int pixels) {// int _alpha = (pixels >> 24) & 0xFF;int _red = (pixels >> 16) & 0xFF;int _green = (pixels >> 8) & 0xFF;int _blue = (pixels) & 0xFF;return (int) (0.3 * _red + 0.59 * _green + 0.11 * _blue);}public static int average(int[] pixels) {float m = 0;for (int i = 0; i < pixels.length; ++i) {m += pixels[i];}m = m / pixels.length;return (int) m;}
}

这里才有的是16*16=256个像素进行对比。

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;import org.apache.commons.lang3.StringUtils;/*** 对图片进行签名* @author tyg* @date   2019年3月28日下午5:12:11*/
public class ImageSign {public static final int SAMEVALUE = 5; // 相同图片阀值public static final int SIMILARVALUE = 10; // 相似图片阀值public static void main(String[] args) {// 开始时间long startMillis = System.currentTimeMillis();String httpUrl = "http://thirdwx.qlogo.cn/mmopen/vi_132";// 多张图片签名moreHttpImageSign(httpUrl);// 单张图片签名String sourceHashCode = getSigleHttpImageSign(httpUrl);System.out.println("sign code: "+sourceHashCode);System.out.println("curMillis:" + (System.currentTimeMillis() - startMillis));}/*** 获取单张图片签名code* @param fileName  (可以是本地文件、网络图片)* @return* @return String* @author tyg* @date   2019年3月28日下午5:31:41*/public static String getSigleHttpImageSign(String fileName) {if (StringUtils.isBlank(fileName)) {return null;}BufferedImage source = fileName.startsWith("http") ? ImageHelper.readHttpJPEGImage(fileName) : ImageHelper.readPNGImage(fileName);if (source == null) {return null;}int width = 16;int height = 16;// 第一步,缩小尺寸。// 将图片缩小到8x8的尺寸,总共64个像素。这一步的作用是去除图片的细节,只保留结构、明暗等基本信息,摒弃不同尺寸、比例带来的图片差异。BufferedImage thumb = ImageHelper.thumb(source, width, height, false);// 第二步,简化色彩。// 将缩小后的图片,转为64级灰度。也就是说,所有像素点总共只有64种颜色。int[] pixels = new int[width * height];for (int i = 0; i < width; i++) {for (int j = 0; j < height; j++) {pixels[i * height + j] = ImageHelper.rgbToGray(thumb.getRGB(i, j));}}// 第三步,计算平均值。// 计算所有64个像素的灰度平均值。int avgPixel = ImageHelper.average(pixels);// 第四步,比较像素的灰度。// 将每个像素的灰度,与平均值进行比较。大于或等于平均值,记为1;小于平均值,记为0。int[] comps = new int[width * height];for (int i = 0; i < comps.length; i++) {if (pixels[i] >= avgPixel) {comps[i] = 1;} else {comps[i] = 0;}}// 第五步,计算哈希值。// 将上一步的比较结果,组合在一起,就构成了一个64位的整数,这就是这张图片的指纹。组合的次序并不重要,只要保证所有图片都采用同样次序就行了。StringBuffer hashCode = new StringBuffer();for (int i = 0; i < comps.length; i += 4) {int result = comps[i] * (int) Math.pow(2, 3) + comps[i + 1] * (int) Math.pow(2, 2)+ comps[i + 2] * (int) Math.pow(2, 1) + comps[i + 2];hashCode.append(binaryToHex(result));}// 得到指纹以后,就可以对比不同的图片,看看64位中有多少位是不一样的。return hashCode.toString();}/*** 传入一张图片,然后与指定目录下的图片做对比* @param httpUrl* @return void* @author tyg* @date   2019年3月28日下午5:06:56*/public static void moreHttpImageSign(String httpUrl) {List<String> hashCodes = new ArrayList<String>();// 网络图片List<String> urlList = collectionImgUrl();String hashCode = null;for (String url : urlList) {hashCode = getSigleHttpImageSign(url);hashCodes.add(hashCode);}System.out.println("Resources: "+hashCodes);String sourceHashCode = getSigleHttpImageSign(httpUrl);System.out.println("Source: "+sourceHashCode);List<String> resultList = new ArrayList<String>();List<String> similarResultList = new ArrayList<String>();List<String> differences = new ArrayList<String>();for (int i = 0; i < hashCodes.size(); i++) {int difference = hammingDistance(sourceHashCode, hashCodes.get(i));if (difference <= SAMEVALUE) {resultList.add(urlList.get(i).substring(urlList.get(i).lastIndexOf("\\") + 1, urlList.get(i).length()));} else if (difference <= SIMILARVALUE) {similarResultList.add(urlList.get(i).substring(urlList.get(i).lastIndexOf("\\") + 1, urlList.get(i).length()));}differences.add(difference + "->"+ urlList.get(i).substring(urlList.get(i).lastIndexOf("\\") + 1, urlList.get(i).length()));}System.out.println("搜索图片:" + httpUrl.substring(httpUrl.lastIndexOf("\\") + 1, httpUrl.length()));System.out.println("相同图片:" + resultList);System.out.println("相似图片:" + similarResultList);System.out.println("图片对比:" + differences);}public static List<String> collectionImgUrl() {String imgPath = "C:\\Users\\lew\\Desktop\\test";List<String> list = new ArrayList<String>();File file = new File(imgPath);if (file.isDirectory()) {String[] fileNames = file.list();for (String name : fileNames) {list.add(imgPath.concat("\\") + name);}}return list;}public static int hammingDistance(String sourceHashCode, String hashCode) {int difference = 0;int len = sourceHashCode.length();for (int i = 0; i < len; i++) {if (sourceHashCode.charAt(i) != hashCode.charAt(i)) {difference++;}}return difference;}private static char binaryToHex(int binary) {char ch = ' ';switch (binary) {case 0:ch = '0';break;case 1:ch = '1';break;case 2:ch = '2';break;case 3:ch = '3';break;case 4:ch = '4';break;case 5:ch = '5';break;case 6:ch = '6';break;case 7:ch = '7';break;case 8:ch = '8';break;case 9:ch = '9';break;case 10:ch = 'a';break;case 11:ch = 'b';break;case 12:ch = 'c';break;case 13:ch = 'd';break;case 14:ch = 'e';break;case 15:ch = 'f';break;default:ch = ' ';}return ch;}
}

java对网络图片进行签名相关推荐

  1. 忽略Java中的自签名证书

    我在职业生涯中遇到过几次问题,就是我们有时希望允许自签名证书用于开发或测试目的. Google的快速搜索显示了多年来无数Java开发人员遇到的麻烦. 根据确切的证书问题,您可能会收到类似以下内容之一的 ...

  2. 写出一下Java方法对应的签名_Java中的方法签名是否包含其返回类型?

    Java类/接口中的方法签名是否包括其返回类型? 例: Java是否知道这两种方法之间的区别: public class Foo { public int  myMethod(int param) { ...

  3. java 手写签名,signature java html5+ 手写签名 源码 Develop 238万源代码下载- www.pudn.com...

    文件名称: signature下载 收藏√  [ 5  4  3  2  1 ] 开发工具: Java 文件大小: 491 KB 上传时间: 2013-08-03 下载次数: 17 提 供 者: 孙晨 ...

  4. [java]飞书机器人签名校验GenSign方法

    飞书的机器人的签名校验比较麻烦,网上找了一圈没找到java版本的获取签名的方法,分享一下,代码如下 public String getSign(String timestamp){//注意timest ...

  5. java.security 框架之签名、加密、摘要及证书

      和第三方系统对接时,需要对隐私数据进行加密,对请求报文进行签名等.加密算法分为单向加密.对称加密.非对称加密等,其对应的算法也各式各样.Java 提供了统一的框架(java.security.*) ...

  6. Java 将网络图片URL 转为file文件

    Java 将网络图片URL 转为file文件;某个需求要求将图片一起导出,图片只有地址,这里将图片先转为file,然后导出excel 代码示例 /*** 将图片转为file** @param url ...

  7. java工程打包时进行签名_使用Java SDK实现离线签名

    严格来说,tx-signer并不属于SDK,它是bytomd中构建交易.对交易签名两大模块的java实现版.因此,若想用tx-signer对交易进行离线签名,需要由你在本地保管好自己的私钥. 如果你的 ...

  8. java ADT生成带签名的apk

    1.生成签名文件 cmd cd到jdk目录下的bin目录. 运行命令: c:\Program Files\Java\jdk1.8.0_05\bin>"keytool.exe" ...

  9. java安全——数字签名+代码签名

    [0]README 1)本文文字描述转自 core java volume 2, 旨在学习 java安全--数字签名 的基础知识: 2)本文实践内容以及截图笔记均为原创: 3)如果要给予applet更 ...

  10. java中远程连接忽略证书_忽略Java中的自签名证书

    java中远程连接忽略证书 我在职业生涯中遇到过几次问题,就是我们有时希望允许自签名证书用于开发或测试目的. Google的快速搜索显示了多年来无数Java开发人员遇到的麻烦. 根据确切的证书问题,您 ...

最新文章

  1. 动力节点Java培训告诉你Java线程的多功能用法
  2. 高职扩招有计算机专业吗,高职扩招计算机专业
  3. C++构造函数与析构函数
  4. Tengine 安装配置全过程
  5. jsoup的Elements类
  6. redis timeout设置多少合适_热水器怎么调温度?一般热水器温度设置多少度比较合适?...
  7. Windows Mobile 6.5 新功能widget开发
  8. 新团队团队融合研讨会_新的网络研讨会:如何避免持续交付的隐性成本
  9. 84键键盘没有insert键
  10. 【Linux】MBR磁盘分区表只能有四个分区?
  11. SQL Server 数据库词汇表
  12. 字母序列号生成 A...Z..AA..ZZ....
  13. jq onclick 定义_jquery onclick函数未定义(jquery onclick function not defined)
  14. c语言51单片机外部中断,51单片机外部中断0实例详解
  15. QMT vs Ptrade 速度对比 (一) 历史行情获取速度
  16. iPad越狱失败 越狱恢复
  17. Spark-Shell 及 Spark-Submit
  18. 解决docker容器因报错无法启动的问题,检查、修复容器错误并重启
  19. python pandas 去重
  20. 图形数据库之Neo4j学习(一)

热门文章

  1. 微信公众号--生成带参数的二维码 {“errcode“:48001,“errmsg“:“api unauthorized rid: 60520af9-71ff2283-63d36e0d“}
  2. 第10章 模糊查询和聚合函数
  3. 每周阅读精选(2013-02-18)
  4. 泰坦尼克 (有剧透)
  5. 美景订餐管理系统--用于公司内部加班订餐
  6. opencv-3.0.0-beta和opencv2版本的区别
  7. 联想电脑键盘M,J,K,L,U,I,O,?按键变成0,1,2,3,4,5,6,+的解决方法
  8. 文件查找工具Everything的使用技巧
  9. echarts自定义legend图例和tooltip默认提示文字
  10. 局域网内如何把文件夹共享