我壓縮圖像在Java中執行Jpeg壓縮,然後在存儲之前調整它們的大小。我保持存儲高度爲480
並根據縱橫比計算出height
,所以保持原來的height:width
比例相同。Java:getHeight()在BufferedImage返回圖像寬度和getWidth()返回圖像高度
這是我使用
String inputImagePath = "1.JPG";
String outputImagePath = "Test Compression\\" + "1.JPG";
File imageFile = new File(inputImagePath);
File compressedImageFile = new File(outputImagePath);
int height = 640;
System.out.print("Conversion Start!\n");
if (imageFile != null)
{
InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);
float quality = 0.2 f;
BufferedImage image = ImageIO.read(is);
double aspectRatio = (double) image.getWidth()/image.getHeight();
width = (int)(height * aspectRatio);
System.out.println("Original height = " + image.getHeight() + " Original width = " + image.getWidth());
System.out.println(" aspect ratio = " + aspectRatio);
System.out.println("height = " + height + " width = " + width + " aspect ratio = " + aspectRatio);
BufferedImage resizedImage = new BufferedImage(width, height, image.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.write(null, new IIOImage(resizedImage, null, null), param);
}
System.out.print("Conversion compete!");
在這裏,代碼在圖像元數據
這裏是打印內容:
Original height = 1920 Original width = 2560
aspect ratio = 1.3333333333333333
height = 480 width = 640
aspect ratio = 1.3333333333333333
我所施加的代碼,以其他圖像,我實際上有width > height
沒有輪換問題。這個rotaion問題只發生在height > width
的圖像上據我所知,在我的代碼中沒有錯,我必須丟失與getHeight()和getWidth()函數有關的東西。請幫助我
你能更新你的身高變量您的代碼示例中呢?它似乎失蹤了。 – Flipbed
我用'height'變量更新代碼。順便提一下,Sergey Grinev建議使用[元數據提取器](https://github.com/drewnoakes/metadata-extractor)獲得期望的結果。我把它貼在下面。 –