| | |
| | | package com.dji.sample.territory.utils; |
| | | |
| | | import com.dji.sample.media.service.impl.FileServiceImpl; |
| | | |
| | | import javax.imageio.ImageIO; |
| | | import javax.imageio.ImageWriteParam; |
| | | import javax.imageio.ImageWriter; |
| | |
| | | BufferedImage image = ImageIO.read(inputFile); |
| | | |
| | | // 计算目标图片的尺寸 |
| | | long targetSizeBytes = targetSizeKB * 1024; |
| | | long targetSizeBytes = targetSizeKB * 1024L; |
| | | long originalSizeBytes = getImageSize(image); |
| | | double compressionRatio = (double) targetSizeBytes / originalSizeBytes; |
| | | int targetWidth = (int) (image.getWidth() * Math.sqrt(compressionRatio)); |
| | |
| | | return 0; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 图片压缩 |
| | | * |
| | | * @param originalImageFile |
| | | * @param compressionQuality 图片压缩质量 0-1 |
| | | * @return |
| | | * @throws IOException |
| | | */ |
| | | public static File compressImageAndGetFile(File originalImageFile, float compressionQuality) throws IOException { |
| | | BufferedImage originalImage = ImageIO.read(originalImageFile); |
| | | try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { |
| | | ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); |
| | | try (ImageOutputStream ios = new MemoryCacheImageOutputStream(baos)) { |
| | | writer.setOutput(ios); |
| | | ImageWriteParam param = writer.getDefaultWriteParam(); |
| | | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); |
| | | param.setCompressionQuality(compressionQuality); |
| | | writer.write(null, new javax.imageio.IIOImage(originalImage, null, null), param); |
| | | } finally { |
| | | writer.dispose(); |
| | | } |
| | | InputStream in = new ByteArrayInputStream(baos.toByteArray()); |
| | | File tempFile = File.createTempFile("compressed-", ".jpg"); |
| | | tempFile.deleteOnExit(); |
| | | Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); |
| | | return tempFile; |
| | | } |
| | | } |
| | | |
| | | public static void main(String[] args) throws IOException { |
| | | String name="test/瑞金图片.jpeg"; |
| | | File file=compressImageAndGetFile(new File("D:\\ideawork\\used-car\\src\\main\\resources\\DJI_20240712113312_0007_V_航点dkbh2_null.jpeg"),0.5F); |
| | | FileServiceImpl.uploadFile("http://139.196.74.78:9000", "sxkj", "sxkj2024", "cloud-bucket", name, file, "image/jpeg"); |
| | | } |
| | | } |