2012-11-02 6 views
1

BufferedImage 클래스를 확장하여 getRed, getBlue, getGreen과 같은 메서드를 추가하여 픽셀 색상을 가져옵니다. 문제는 내 원본 이미지가 확장 된 객체가 아닌 BufferedImage 객체라는 점입니다. 확장 된 데이터 형식으로 변환하려고하면 작동하지 않습니다. 내 영어BufferedImage 클래스의 확장

는이 오류를 얻을 미안 부모 클래스에서 캐스팅하려고

Exception in thread "main" java.lang.ClassCastException: java.awt.image.BufferedImage cannot be cast to asciiart.EBufferedImage 

코드

EBufferedImage character = (EBufferedImage)ImageClass.charToImage(letter, this.matrix_x, this.matrix_y); 

내 확장 한 클래스

public class EBufferedImage extends BufferedImage 
{ 
public EBufferedImage(int width, int height, int imageType) 
{ 
    super(width,height,imageType); 
} 

/** 
* Returns the red component in the range 0-255 in the default sRGB 
* space. 
* @return the red component. 
*/ 
public int getRed(int x, int y) { 
    return (getRGB(x, y) >> 16) & 0xFF; 
} 

/** 
* Returns the green component in the range 0-255 in the default sRGB 
* space. 
* @return the green component. 
*/ 
public int getGreen(int x, int y) { 
    return (getRGB(x, y) >> 8) & 0xFF; 
} 

/** 
* Returns the blue component in the range 0-255 in the default sRGB 
* space. 
* @return the blue component. 
*/ 
public int getBlue(int x, int y) { 
    return (getRGB(x, y) >> 0) & 0xFF; 
} 
} 
+0

단순히 개체를 아닌 유형으로 캐스팅 할 수 없습니다. 그것은 결코 작동하지 않을 것입니다. 대신에 클래스에 BufferedImage 객체를 받아들이고 전달 된 BufferedImage를 기반으로 객체의 인스턴스를 만드는 생성자를 제공하는 것이 좋을까요? –

답변

2

을 설치해야 커플 옵션 :

  1. BufferedImage을 허용하는 확장 클래스에 생성자를 추가하고 모든 것을 적절하게 설정합니다.

    public class ExtendedBufferedImage extends BufferedImage{ 
    
        public ExtendedBufferedImage(BufferedImage image){ 
         //set all the values here 
        } 
    
        //add your methods below 
    } 
    

    이 것은 많은 문제와 잠재적 인 것처럼 보입니다. 어떤 변수를 설정하는 것을 잊어 버리면 이상한 버그가 생기거나 필요한 정보를 잃을 수 있습니다.

  2. 은 당신의 방법을 추가 한 다음 BufferedImage의 인스턴스가있는 래퍼 클래스를 생성합니다.

    public class ExtendedBufferedImage{ 
        private BufferedImage image; 
    
        public ExtendedBufferedImage(BufferedImage image){ 
        this.image = image; 
        } 
    
        //add your methods below 
    } 
    

    이 매우 합리적이며, diffcult하지 않는 것입니다. BufferedImage을 공개하거나 getter 메소드를 추가하면 필요할 경우 실제 BufferedImage을 얻을 수 있습니다.

  3. 메서드가 정적 인 유틸리티 클래스를 만들고 BufferedImage을 매개 변수로 전달하십시오.

    public class BufferedImageUtil{ 
    
        public static int getRed(BufferedImage image, int x, int y) { 
        return (image.getRGB(x, y) >> 16) & 0xFF; 
        } 
    
        //add your other methods 
    } 
    

    어떤 사람들은 유틸리티 클래스를 좋아하지 않지만 나는 이런 종류의 것들을 좋아합니다. 이 방법들을 온 곳에서 사용할 계획이라면, 이것이 좋은 선택이라고 생각합니다.

는 개인적으로 난 유틸리티 클래스 경로를 이동하지만, 옵션 2에서 수행대로 다음을 포장하는 마음에 들지 않는 경우와 마찬가지로 작동합니다.

+0

당신이 옳습니다. 나는 두 번째 해결책을 사용할 것이다. 첫 번째 솔루션에서는 모든 매개 변수를 올바르게 설정하는 것이 까다로울 수 있습니다. 고맙습니다 –