Java 图片压缩:轻松将图片压缩至 100KB 以内
要将图片压缩至 100KB 以内,可以使用 Java 的图像处理库,如 ImageIO 和 BufferedImage。下面是一个示例代码,演示如何将图片压缩至 100KB 以内:\n\njava\nimport java.awt.Graphics2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic class ImageCompressor {\n\n public static void main(String[] args) {\n try {\n // 读取原始图片文件\n File originalImageFile = new File("original.jpg");\n BufferedImage originalImage = ImageIO.read(originalImageFile);\n\n // 计算原始图片的尺寸\n int originalWidth = originalImage.getWidth();\n int originalHeight = originalImage.getHeight();\n\n // 计算压缩比例\n double compressionRatio = 1;\n\n // 如果原始图片大小超过目标大小,则进行压缩\n if (originalImageFile.length() > 100 * 1024) {\n compressionRatio = (100.0 * 1024) / originalImageFile.length();\n }\n\n // 计算压缩后的图片尺寸\n int compressedWidth = (int) (originalWidth * compressionRatio);\n int compressedHeight = (int) (originalHeight * compressionRatio);\n\n // 创建压缩后的图片对象\n BufferedImage compressedImage = new BufferedImage(compressedWidth, compressedHeight, originalImage.getType());\n\n // 绘制压缩后的图片\n Graphics2D graphics = compressedImage.createGraphics();\n graphics.drawImage(originalImage, 0, 0, compressedWidth, compressedHeight, null);\n graphics.dispose();\n\n // 输出压缩后的图片文件\n File compressedImageFile = new File("compressed.jpg");\n ImageIO.write(compressedImage, "jpg", compressedImageFile);\n\n System.out.println("图片压缩完成!");\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\n\n该示例代码会读取名为"original.jpg"的原始图片文件,并将其压缩至 100KB 以内,最终输出为名为"compressed.jpg"的压缩后的图片文件。\n\n请注意,压缩比例的计算方式是通过目标大小除以原始大小,然后将该比例应用于原始图片的尺寸。如果原始图片本身已经小于目标大小,则不会进行压缩。
原文地址: https://www.cveoy.top/t/topic/qgEZ 著作权归作者所有。请勿转载和采集!