旋转BufferedImage

时间:2013-10-07 19:17:58

标签: java image bufferedimage

我正在关注一本教科书并且已经陷入困境。

这是一个控制台应用程序。

我有以下类使用旋转图像方法:

public class Rotate  {
    public ColorImage rotateImage(ColorImage theImage) {
        int height = theImage.getHeight();
        int width = theImage.getWidth();
        ColorImage rotImage = new ColorImage(height, width); //having to create new obj instance to aid with rotation
        for (int y = 0; y < height; y++) { 
            for (int x = 0; x < width; x++) {
                Color pix = theImage.getPixel(x, y);
                rotImage.setPixel(height - y - 1, x, pix);
            }
        }
       return rotImage; //I want this to return theImage ideally so I can keep its state
    }
}

旋转工作,但我必须创建一个新的ColorImage(下面的类),这意味着我正在创建一个新的对象实例(rotImage)并丢失我传入的对象的状态(theImage)。目前,这并不是什么大不了的事,因为ColorImage并不是很重要,但是如果我想让它保持已经应用的旋转次数,或者我正在失去所有这些东西的列表。

以下课程来自教科书。

public class ColorImage extends BufferedImage
{

    public ColorImage(BufferedImage image)
    {
        super(image.getWidth(), image.getHeight(), TYPE_INT_RGB);
        int width = image.getWidth();
        int height = image.getHeight();
        for (int y=0; y < height; y++)
            for (int x=0; x < width; x++)
                setRGB(x, y, image.getRGB(x,y));
    }


    public ColorImage(int width, int height)
    {
        super(width, height, TYPE_INT_RGB);
    }


    public void setPixel(int x, int y, Color col)
    {
        int pixel = col.getRGB();
        setRGB(x, y, pixel);
    }


    public Color getPixel(int x, int y)
    {
        int pixel = getRGB(x, y);
        return new Color(pixel);
    }
}

我的问题是,如何旋转我传入的图像以便保存其状态?

1 个答案:

答案 0 :(得分:2)

除非您将自己局限于方形图像或180°旋转,否则您需要一个新对象,因为尺寸会发生变化。 BufferedImage对象的维度一旦创建,就是不变的。

  

如果我想让它保留已经应用的旋转次数或者我正在失去所有那些东西的列表

您可以创建另一个类来保存其他信息以及ColorImage / BufferedImage,然后将ColorImage / BufferedImage类本身限制为仅保留像素。一个例子:

class ImageWithInfo {
    Map<String, Object> properties; // meta information
    File file; // on-disk file that we loaded this image from
    ColorImage image; // pixels
}

然后你可以自由地替换像素对象,同时保留其他状态。 favor composition over inheritance通常会有所帮助。简而言之,这意味着,而不是扩展一个类,创建一个单独的类,其中包含原始类作为字段。

另请注意,您图书中的轮播实施似乎主要用于学习目的。它很好,但是如果你操纵非常大的图像或者以动画速度连续图形旋转,它将显示其性能限制。