ImageUtil.java 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package com.fdkankan.common.constant;
  2. import cn.hutool.core.img.ImgUtil;
  3. import javax.imageio.ImageIO;
  4. import java.awt.image.BufferedImage;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.IOException;
  9. /**
  10. * <p>
  11. * TODO
  12. * </p>
  13. *
  14. * @author dengsixing
  15. * @since 2022/4/8
  16. **/
  17. public class ImageUtil {
  18. public static final String TYPE_JPG = "jpg";
  19. public static final String TYPE_GIF = "gif";
  20. public static final String TYPE_PNG = "png";
  21. public static final String TYPE_BMP = "bmp";
  22. public static final String TYPE_UNKNOWN = "unknown";
  23. public static boolean isImage(FileInputStream fis){
  24. String picType = getPicType(fis);
  25. if(TYPE_JPG.equals(picType)
  26. || TYPE_GIF.equals(picType)
  27. || TYPE_PNG.equals(picType)
  28. || TYPE_BMP.equals(picType)){
  29. return true;
  30. }
  31. return false;
  32. }
  33. public static String getPicType(FileInputStream fis) {
  34. // 读取文件的前几个字节来判断图片格式
  35. byte[] b = new byte[4];
  36. try {
  37. fis.read(b, 0, b.length);
  38. String type = bytesToHexString(b).toUpperCase();
  39. if (type.contains("FFD8FF")) {
  40. return TYPE_JPG;
  41. } else if (type.contains("89504E47")) {
  42. return TYPE_PNG;
  43. } else if (type.contains("47494638")) {
  44. return TYPE_GIF;
  45. } else if (type.contains("424D")) {
  46. return TYPE_BMP;
  47. } else {
  48. return TYPE_UNKNOWN;
  49. }
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. } finally {
  53. if (fis != null) {
  54. try {
  55. fis.close();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. }
  61. return null;
  62. }
  63. public static String bytesToHexString(byte[] src) {
  64. StringBuilder stringBuilder = new StringBuilder();
  65. if (src == null || src.length <= 0) {
  66. return null;
  67. }
  68. for (int i = 0; i < src.length; i++) {
  69. int v = src[i] & 0xFF;
  70. String hv = Integer.toHexString(v);
  71. if (hv.length() < 2) {
  72. stringBuilder.append(0);
  73. }
  74. stringBuilder.append(hv);
  75. }
  76. return stringBuilder.toString();
  77. }
  78. public static void main(String[] args) throws IOException {
  79. ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
  80. String path = "G:\\home\\backend\\4dkankan_v4\\sale\\file\\sale\\file\\test\\5474a1e8d93747f3aec79e6021c10a3b.png";
  81. String picType = getPicType(new FileInputStream(path));
  82. System.out.println(picType);
  83. BufferedImage read = ImgUtil.read(new File(path));
  84. ImageIO.write(read, "png", byteArrayOut);
  85. }
  86. }