我正在学习一本教科书,并且已经被困在了一个特定的点上。
这是一个控制台应用程序。
下面是一个旋转图像方法的类:
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没有太多的房子,但如果我想要它容纳的状态,比如说,它已经申请的旋转次数,或者一个清单,我正在失去所有这些东西。
下面的课是课本上的。
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);
}
}我的问题是,我如何旋转我传入的图像,以保持它的状态?
发布于 2013-10-07 22:07:59
除非你限制自己的平方图像或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很有帮助。简而言之,这意味着,与其扩展类,不如创建一个单独的类,其中包含作为字段的原始类。
还请注意,您的书中的轮换实现似乎主要是为了学习目的。这是好的,但将显示它的性能限制,如果你操纵非常大的图像或连续的图形旋转的动画速度。
https://stackoverflow.com/questions/19232790
复制相似问题