2013-10-07 159 views
1

我正在關注教科書,並陷入了一個特定的問題。旋轉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); 
    } 
} 

我的問題是,我如何旋轉我傳入的圖像,以便我可以保持其狀態?

+0

你真的不能沒有把它包裝在像你一樣的對象中,或者發明你自己的圖像格式,或者做類似於速記的事情,並將狀態信息隱藏在已經使用過的格式中。 – arynaq

+0

@arynaq我認爲你的意思是'隱寫術'。 – EJP

+0

@EJP我最肯定的是:D – arynaq

回答

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有幫助。簡而言之,這意味着,不是擴展一個類,而是創建一個單獨的類,其中包含原始類作爲字段。

另請注意,您書中的旋轉實現似乎主要用於學習目的。這很好,但是如果您操作非常大的圖像或以動畫速度連續顯示圖形,則會顯示其性能限制。

+0

是的,這似乎是唯一的方法。我特別讚賞其他信息,「一旦創建,BufferedImage對象的維度就是不變的。」這確實清除了很多。 – TEK