在Java中放大和缩小图像

在Java中放大和缩小图像,java,image,image-processing,zooming,Java,Image,Image Processing,Zooming,我认为这个问题是不言自明的。我想使用JSlider实现一个简单的缩放功能,比如在Windows Live照片库中 我在网上快速浏览了一下,但是当我将代码复制到Eclipse中时,我尝试使用的所有代码似乎都有错误。我也不想使用第三方库,因为应用程序可能以公司名称出售。另外,我开始意识到可能需要一些安全预防措施来防止错误,但我不知道这些是什么 因此,如果有人能提供一些Java代码来放大和缩小图像,我将不胜感激 另外,我计划将图像用作JLabel内部的ImageIcon,该图标将添加到JScrollP

我认为这个问题是不言自明的。我想使用
JSlider
实现一个简单的缩放功能,比如在Windows Live照片库中

我在网上快速浏览了一下,但是当我将代码复制到Eclipse中时,我尝试使用的所有代码似乎都有错误。我也不想使用第三方库,因为应用程序可能以公司名称出售。另外,我开始意识到可能需要一些安全预防措施来防止错误,但我不知道这些是什么

因此,如果有人能提供一些Java代码来放大和缩小图像,我将不胜感激


另外,我计划将图像用作
JLabel
内部的
ImageIcon
,该图标将添加到
JScrollPane

,通过对原始图像进行缩放变换,您可以轻松实现这一点。 假设当前图像宽度
newImageWidth
,当前图像高度
newImageHeight
,以及当前缩放级别
zoomLevel
,则可以执行以下操作:

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

您也可以按如下方式使用它 :


感谢GETah,我已经在我的代码中有了一个方法来实现这一点,它只是没有让我觉得它也可以用于此目的,但正如我刚刚测试的那样——它显然可以!啊,等等,这种方法似乎影响了图像的透明度(透明位是黑色的),你知道为什么以及如何解决这个问题吗?@Andy似乎使用仿射变换应该保持图像的透明度。。。看看这个
public class ImageLabel extends JLabel{
    Image image;
    int width, height;

    public void paint(Graphics g) {
        int x, y;
        //this is to center the image
        x = (this.getWidth() - width) < 0 ? 0 : (this.getWidth() - width);
        y = (this.getHeight() - width) < 0 ? 0 : (this.getHeight() - width);

        g.drawImage(image, x, y, width, height, null);
    }

    public void setDimensions(int width, int height) {
        this.height = height;
        this.width = width;

        image = image.getScaledInstance(width, height, Image.SCALE_FAST);
        Container parent = this.getParent();
        if (parent != null) {
            parent.repaint();
        }
        this.repaint();
    }
}
public void zoomImage(int zoomLevel ){
    int newWidth, newHeight, oldWidth, oldHeight;
    ImagePreview ip = (ImagePreview) jLabel1;
    oldWidth = ip.getImage().getWidth(null);
    oldHeight = ip.getImage().getHeight(null);

    newWidth = oldWidth * zoomLevel/100;
    newHeight = oldHeight * zoomLevel/100;

    ip.setDimensions(newHeight, newWidth);
}