今天在做二维码的时候,要在二维码中心放置一个logo图标,当时用ImageIO读取的时候始终为空。最后发现是图片格式问题。

整个class代码,utils:

package com.allk.utils;import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;import javax.imageio.ImageIO;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/*** @Author Darren* @Time 2017年9月5日 上午10:57:14* @Description:二维码生成/解析*/
@Component
public class QRCodeUtils {public static String QRCode$imagePath;/** 图片格式 */public static final String QRCODE_PNG = "png";public static final String QRCODE_JPG = "jpg";public static final String QRCODE_GIF = "gif";public static final String QRCODE_BMP = "bmp";public static final String QRCODE_JPEG = "jpeg";public static final String QRCODE_PNM = "pnm";private static final Integer QRCode$width = 200;private static final Integer QRCode$height = 200;private static final int QRCOLOR = 0xFF000000; // 默认是黑色private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色/**二维码扫描请求链接,验证是否有效(优惠券)*/public static final String QRCode$DimensionalCodeUrl="http://10.192.1.125:8081/dimensionalCode/verifyCode.do/";/** 二维码logo图片,默认使用logo图片 */public static final String QRCode$logoImg = "/pinklogo.jpg";/*** 不带logo的二维码* * @param text 二维码附带的信息* @param path 要存放二维码图片的路径* @param format 图片格式 /jpg,png,gif..........* @param file 需要显示在二维码中心位置的小图标(图片)* @throws Exception* @throws WriterException* @throws IOException*/public static final String[] createQRCode(String text, String path, String format)throws WriterException, IOException {BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, QRCode$width, QRCode$height,getDecodeHintType());String serverImgName = createServerImgName();String filePath = path + "/" + serverImgName;File outputFile = new File(filePath);MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);// 生成不带中心位置图标的二维码图片String[] img = new String[3];img[0] = serverImgName;img[1] = String.valueOf(QRCode$width);img[2] = String.valueOf(QRCode$height);return img;}/*** 带logo的二维码* * @param text 二维码附带的信息* @param path 要存放二维码图片的路径* @param format 图片格式 /jpg,png,gif..........* @param file 需要显示在二维码中心位置的小图标(图片)* @throws Exception* @throws WriterException* @throws IOException*/public static final String[] createLogoQRCode(String text, String path, String format, File file)throws WriterException, IOException {BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, QRCode$width, QRCode$height,getDecodeHintType());int w = bitMatrix.getWidth();int h = bitMatrix.getHeight();BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色for (int x = 0; x < w; x++) {for (int y = 0; y < h; y++) {image.setRGB(x, y, bitMatrix.get(x, y) ? QRCOLOR : BGWHITE);}}BufferedImage bufferedImage = null;if (file != null) {bufferedImage = encodeImgLogo(image, file);// 绘制二维码自定义中心位置图片,注意实际格式,更改图片后缀名为满足的格式无效} else {// logo图片String logoPath = path + QRCode$logoImg;bufferedImage = encodeImgLogo(image, new File(logoPath));// 绘制二维码中心位置logo图片}if (bufferedImage == null) {return null;}// 重新生成带logo的二维码图片String imgName = createServerImgName();String QRClogCode = path + "/" + imgName;ImageIO.write(bufferedImage, format, new File(QRClogCode));// 生成带中心位置图标的二维码图片String[] img = new String[3];img[0] = imgName;img[1] = String.valueOf(QRCode$width);img[2] = String.valueOf(QRCode$height);return img;}/*** 解析二维码,需要javase包。 文件方式解码* * @param file* @return*/public static String decode(File file) {BufferedImage image;try {if (file == null || file.exists() == false) {throw new Exception(" File not found:" + file.getPath());}image = ImageIO.read(file);return unifiedDecode(image);} catch (Exception e) {e.printStackTrace();}return null;}/*** 解析二维码 流方式解码* * @param input* @return*/public static String decode(InputStream input) {BufferedImage image;try {if (input == null) {throw new Exception(" input is null");}image = ImageIO.read(input);return unifiedDecode(image);} catch (Exception e) {e.printStackTrace();}return null;}private static String unifiedDecode(BufferedImage image) throws NotFoundException {LuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;// 解码设置编码方式为:utf-8,Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();hints.put(DecodeHintType.CHARACTER_SET, "utf-8");result = new MultiFormatReader().decode(bitmap, hints);return result.getText();}/*** 生成文件名* @return*/public static final String createServerImgName() {UUID serverImgUuid = UUID.randomUUID();return DateFormatterUtils.getDateTime() + serverImgUuid.toString();// 文件名}/*** 设置二维码的格式参数* * @return*/public static Map<EncodeHintType, Object> getDecodeHintType() {// 用于设置QR二维码参数Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();// 设置QR二维码的纠错级别(H为最高级别)具体级别信息hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置编码方式hints.put(EncodeHintType.CHARACTER_SET, "utf-8");hints.put(EncodeHintType.MARGIN, 0);hints.put(EncodeHintType.MAX_SIZE, 350);hints.put(EncodeHintType.MIN_SIZE, 100);return hints;}/*** 二维码绘制logo* * @param image* @param logoImg*            logo图片文件 格式:JPG, jpg, tiff, pcx, PCX, bmp, BMP, gif, GIF,*            WBMP, png, PNG, raw, RAW, JPEG, pnm, PNM, tif, TIF, TIFF,*            wbmp, jpeg* @throws IOException*/public static BufferedImage encodeImgLogo(BufferedImage image, File logoImg) throws IOException {// String[] names = ImageIO.getReaderFormatNames();// System.out.println(Arrays.toString(names));// 能读取的图片格式:JPG, jpg, tiff, pcx, PCX, bmp, BMP, gif, GIF, WBMP, png, PNG, raw, RAW, JPEG, pnm, PNM, tif, TIF, TIFF, wbmp, jpeg// 读取二维码图片// 获取画笔Graphics2D g = image.createGraphics();// 读取logo图片BufferedImage logo = ImageIO.read(logoImg);// 设置二维码大小,太大,会覆盖二维码,此处20%int logoWidth = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10): logo.getWidth(null);int logoHeight = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10): logo.getHeight(null);// 设置logo图片放置位置// 中心int x = (image.getWidth() - logoWidth) / 2;int y = (image.getHeight() - logoHeight) / 2;// 右下角,15为调整值// int x = twodimensioncode.getWidth() - logoWidth-15;// int y = twodimensioncode.getHeight() - logoHeight-15;// 开始合并绘制图片g.drawImage(logo, x, y, logoWidth, logoHeight, null);g.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);// logo边框大小g.setStroke(new BasicStroke(2));// logo边框颜色g.setColor(Color.WHITE);g.drawRect(x, y, logoWidth, logoHeight);g.dispose();logo.flush();image.flush();return image;}public String getQRCode$imagePath() {return QRCode$imagePath;}@Value("${upload.path}")public void setQRCode$imagePath(String qRCode$imagePath) {QRCode$imagePath = qRCode$imagePath;}}

// String[] names = ImageIO.getReaderFormatNames();
// System.out.println(Arrays.toString(names));
// 能读取的图片格式:JPG, jpg, tiff, pcx, PCX, bmp, BMP, gif, GIF, WBMP, png, PNG, raw, RAW, JPEG, pnm, PNM, tif, TIF, TIFF, wbmp, jpeg

在236行那里ImageIO.read(logoImg)读取logo的时候得到的一直是null,百思不得其解。网上也查看了很多都没有错,最终发现是图片格式问题
最开始是一张后缀为ico的图片,将其改为了jpg,还是不行。ImageIO读取的时候并不是以后缀名格式来读取,所以改后缀名没有用,因为实际的图片格式并没有更改。
ImageIO读取的格式以实际的图片格式为准。读取图片的实际格式要满足上面的格式才可以进行读取,改后缀名无效。否则就是空,也不会报错。

希望对遇到此类问题的同志们有用





												

ImageIO javax.imageio;读取图片问题相关推荐

  1. java读取图片缩略方法_java 图片缩略图的两种方法

    最近网上看到两种不同的java图片缩略图的绘制方案 第一种,使用Graphics().drawImage按照一定的比例重新绘制图像. Java代码 package com.image.suoluetu ...

  2. java读取图片画布大小_Java图像文件的读写

    读取bmp文件到BufferedImage中 File file2 = new File("c:\\testimages\\tttt" + ".bmp"); / ...

  3. 使用javax.imageio.ImageIO读取JPEG图片时出现异常java.awt.color.CMMException: General CMM error517

    目录 问题描述 背景 异常 解决 重现 紧急处理 解决方法 第一种:变更JDK版本 第二种:去掉引入的twelvemonkeys图片读取插件 问题描述 背景 由于业务需要,生产环境需要将用户上传的图片 ...

  4. 使用com.sun.imageio.plugins.png.PNGMetadata读取图片的元数据

    所谓图片元数据,就是除了我们肉眼看到的图片内容外,隐藏在这些内容背后的一些技术数据. 本文介绍如何使用Java代码将一张图片的隐藏信息读取出来. 首先不需要下载任何额外的Java库,用JDK自带的库就 ...

  5. 使用com.sun.imageio.plugins.png.PNGMetadata读取图片的元数据 1

    所谓图片元数据,就是除了我们肉眼看到的图片内容外,隐藏在这些内容背后的一些技术数据. 本文介绍如何使用Java代码将一张图片的隐藏信息读取出来. 首先不需要下载任何额外的Java库,用JDK自带的库就 ...

  6. java图片处理---Javax.imageIO包的用法

    转自:https://blog.csdn.net/fanhenghui/article/details/70200901 Java中进行图像I/O(即读图片和写图片,不涉及到复杂图像处理)有三个方法: ...

  7. Freemarker下载Word文档(文字+图片+表格)Idea示例 (附word展示图片异常解决方案)(附JPEG格式图片通过imageio.read方法读取为null解决方案)

    流程:拿到word模板 转为ftl格式并填充占位符参数,调用java代码填充参数即可 (文末附word打开图片显示异常,wps打开却显示正常的解决方案) (文末附Jpeg格式图片获取为null解决方案 ...

  8. 图片处理 javax.imageio.IIOException: Unsupported Image Type

    2019独角兽企业重金招聘Python工程师标准>>> 图片处理 javax.imageio.IIOException: Unsupported Image Type 博客分类: j ...

  9. ImageIO.read(inputStream)读取.webp格式图片报错

    0.码仙励志 莫妒他长,妒长,则己终是短.莫护己短,护短,则己终不长. 1.问题描述 今天测试提了一个新bug,查找原因是因为测试上传了一张.webp格式的图片. 在代码运行到 javax.image ...

最新文章

  1. MySQL 唯一索引和普通索引该如何选择?
  2. KOFLive Beta Daily-Scrum 8
  3. Java导出基础 用POI导出Excel
  4. 第五章 MongoDb索引优化 5.4
  5. C语言六边形蜂巢数组,android 六边形蜂巢布局控件
  6. Android开发 ---多线程操作:Handler对象,消息队列,异步任务下载
  7. Knative 初体验:Serving Hello World
  8. 运用python的方式_对Python使用mfcc的两种方式详解
  9. 从零开始学前端:标签渐变和媒体查询 --- 今天你学习了吗?(CSS:Day25)
  10. hdu 2295 Radar DLX 重复覆盖问题
  11. 远程修改服务器登录密码,远程服务器修改登录密码
  12. 冯乐乐之一 图形学基础 Shader入门精要
  13. Java 合并 取消合并 Excel 单元格
  14. 自定义Java注解处理器
  15. 【Metasploit】MSF常用命令
  16. python与开源gis_转载《Python与开源GIS教程》随书源码网址
  17. socket 10053 错误
  18. 不是封闭也不是开放 创新封闭式基金迎来变种
  19. 在Java 应用程序中访问USB设备
  20. 永磁同步电机(PMSM)的转子结构剖析

热门文章

  1. 信息系统面临的安全威胁
  2. hadoop安装-redhat
  3. C语言Hello World
  4. CityMaker学习教程02 软件的授权
  5. 8.编写程序,要求如下: 定义名为VolumeArea的抽象类,在其中定义圆周率的值为3.14159,并定义两个抽象方法volume(double r)和area(double r),它们的返回
  6. CodeForces - 1367
  7. 串的匹配 (KPM算法由来引导)
  8. linux 中的.so和.a文件
  9. matlab 古典概率求解,第1章数学建模古典概型解答.ppt
  10. Android中notifyDataSetInvalidated()和notifyDataSetChanged()