我正在阅读一本教科书,但陷入了某个特定的点。
这是一个控制台应用程序。
我有以下具有旋转图像方法的类:
public class Rotate {
public ColorImage rotateImage(ColorImage theImage) {
int height = theImage.getHeight();
int width = theImage.getWidth();
//having to create new obj instance to aid with rotation
ColorImage rotImage = new ColorImage(height, width);
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);
}
}
//I want this to return theImage ideally so I can keep its state
return rotImage;
}
}
旋转有效,但我必须创建一个新的 ColorImage (下面的类),这意味着我正在创建一个新的对象实例 (rotImage) 并丢失我传入的对象 (theImage) 的状态。目前,这不是什么大问题,因为 ColorImage 容纳的内容不多,但如果我希望它容纳其已应用的旋转次数或某些内容的列表等状态,我就会失去所有这些。
下面的类(class)来自课本。
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);
}
}
我的问题是,如何旋转传入的图像以便保留其状态?
最佳答案
除非您将自己限制为方形图像或 180° 旋转,否则您需要一个新对象,因为尺寸会发生变化。 BufferedImage 对象的尺寸一旦创建,就保持不变。
If I wanted it to house the state of, say, number of rotations it has had applied or a List of something I'm losing all that
您可以创建另一个类来保存其他信息以及 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 有帮助。简而言之,这意味着,不要扩展类,而是创建一个单独的类,其中包含原始类作为字段。
另请注意,您书中的轮换实现似乎主要用于学习目的。这很好,但如果您操作非常大的图像或以动画速度连续图形旋转,则会显示出其性能限制。
关于java - 旋转缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19232790/