用Java放大和缩小图像

问题描述:

我认为这个问题非常自我解释,我想使用 JSlider 来实现简单的缩放功能,例如在Windows Live Photo Gallery中。

I think the question is quite self-explainitory, I want to implement a simple zoom function using a JSlider like in Windows Live Photo Gallery for instance.

我在网上看了一下,但我尝试使用的所有代码在将其复制到eclipse时似乎都有错误。我真的不想使用第三方库,因为该应用程序可能以公司名称出售。另外,我开始意识到为了防止错误可能需要一些安全预防措施,但我不知道它们会是什么。

I've had a quick look online but all the code I've tried to use appears to have errors in when I copy it into eclipse. I don't really want to use a third party library either as the application may be sold under a company name. Plus, I'm begginning to realise that there may be some safety precations required in order to prevent errors, but I do not know what these will be.

所以,如果任何人都可以为我提供一些Java代码来放大和缩小图片,我们会非常感激。

So, if anybody can provide me with some Java code to zoom in and out of images it would be grately appreciated.

提前致谢

PS我打算在 JLabel 中使用Image作为 ImageIcon ,这将被添加到 JScrollPane

PS I plan to use the Image as an ImageIcon inside of a JLabel which will be added to a JScrollPane

您可以通过使用缩放变换轻松实现此目的原始图像。
假设当前图像宽度 newImageWidth ,当前图像高度 newImageHeight ,以及当前缩放级别 zoomLevel ,您可以执行以下操作:

You can easily achieve this by using scale transforms on the original image. Assuming your the current image width newImageWidth, and the current image height newImageHeight, and the current zoom level zoomLevel, you can do the following:

int newImageWidth = imageWidth * zoomLevel;
int newImageHeight = imageHeight * zoomLevel;
BufferedImage resizedImage = new BufferedImage(newImageWidth , newImageHeight, imageType);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newImageWidth , newImageHeight , null);
g.dispose();

现在,替换原始图像, originalImage ,在您的显示区域中 resizedImage

Now, replace the original image, originalImage, in your display area by resizedImage.