我有一个图像 (147 KB),我想将其缩小到 100 KB 以下。下面的代码尝试执行此操作,但是当图像在另一侧出现时,宽度和高度会缩小,但图像上的磁盘空间从 147 变为 250!它应该变得更小而不是更高......
你能告诉我为什么这段代码没有这样做吗?
谢谢
//Save image
BufferedImage resizeImagePng = resizeImage(originalImage, type, newLargeImageLocation);
//Resize and save
ImageIO.write(resizeImagePng, "png", new File(newSmallImageLocation));
//Create new image
private static BufferedImage resizeImage(BufferedImage originalImage, int type, String newLargeLocation) throws Exception{
//Get size of image
File file =new File(newLargeLocation);
//File size in KBs
double bytes = file.length();
double kiloBytes = bytes/1024;
double smallWidth = originalImage.getWidth();
double smallHeight = originalImage.getHeight();
double downMult = 1;
//If image is too large downsize to fit the size
if (kiloBytes>MAX_IMAGE_SIZE_IN_KYLOBITES) {
downMult = MAX_IMAGE_SIZE_IN_KYLOBITES/kiloBytes;
smallWidth *= downMult;
smallHeight *= downMult;
}
//Final dimensions
int finalHeight = (int)smallHeight;
int finalWidth = (int)smallWidth;
//Init after
BufferedImage after = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_ARGB);
//Scale
AffineTransform at = new AffineTransform();
at.scale(downMult, downMult);
//Scale op
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(originalImage, after);
//Return after
return after;
}
最佳答案
2 个问题,我也有一个调整大小程序,但我调整图像的大小有点不同:
首先,我从名为“original”的 BufferedImage 对象开始创建一个 Dimension 对象(不是真正需要的,但从设计角度来说似乎更好一些)
final int width = original.getWidth();
final int height = original.getHeight();
final Dimension d = new Dimension(width, height);
就我而言,这与文件大小无关,而是与最大宽度和/或高度有关,因此,在不深入细节的情况下,我根据上面创建的对象计算一个新的 Dimension 对象。 新的 Dimension 对象称为“缩放”。
这就是我获取新的缩放缓冲图像的方法:
public BufferedImage resizeExact(final BufferedImage original, final Dimension scaled, final Dimension offset) {
final Image newImage = original.getScaledInstance(scaled.width, scaled.height, Image.SCALE_SMOOTH);
final BufferedImage bufferedImage = new BufferedImage(newImage.getWidth(null),
newImage.getHeight(null),
BufferedImage.TYPE_INT_BGR);
bufferedImage.createGraphics().drawImage(newImage, offset.width, offset.height, null);
return bufferedImage;
}
使用此代码,我获得一个名为 resizedImage 的 BufferedImage,需要将其写入 OutputStream 输出,为此我使用此代码:
ImageIO.write(resized, "jpg", out);
out.close();
这里我讨论第二个问题:我使用标准 ImageIO 类将 BufferedImage 编写为 jpeg 文件。这里的问题是 JPEG 编码器通常使用压缩因子,因子越高,生成的文件越小,但生成的文件的质量损失越大。该代码使用默认的压缩系数 70%。这很适合我。但是,如果您想更改此设置,此引用文献解释了如何执行此操作:Setting jpg compression level with ImageIO in Java 。请注意,此处将其更改为 100% 本质上是较低的压缩系数。
您的代码片段没有显示您最终如何创建 jpeg 文件(我假设您也使用 jpeg)。如果你的原始图像被压缩,比如说40%的比例(不太可能,因为那样你会得到一个糟糕的图像,我假设)所以未jpeged你有100%,如果你想将文件大小减少到80%,你就减少图像大小到 80%,如果您随后使用 70% 压缩系数对其进行压缩,您的最终结果将约为 56%,这比 40% 更大。
希望这有帮助。但是,如果您指定如何编写 jeg 图像(可能使用 javax.imageio 标准之外的其他库),则可能有另一种方法来指定压缩因子。
关于java - 使 bufferedImage 变小的代码出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18496187/