2016-01-28 4 views
-1

Мне нужно создать новый экземпляр класса SimpleRGB, который был создан для того, чтобы изменить пиксели изображения на один цвет. Я знаю, что я неправильно создаю экземпляр, но не могу понять, как это сделать правильно.Хотите создать новый экземпляр моего класса

/** 
* Get the NEW image containing only the red color. The red values of this 
* new image should be exactly the same as red value of this image. The 
* green and blue values of this new image should be 0s. 
* 
* @return the NEW image (SimpleRGB) containing only the red color of this 
* image. 
*/ 
public SimpleRGB getRedImage() { 
    SimpleRGB redImage = new SimpleRGB(aRed); 
    return redImage; 
} 

Это полный Class

общественного класса SimpleRGB {

private int aWidth; 
private int aHeight; 
private int[][] aRed; 
private int[][] aBlue; 
private int[][] aGreen; 


public SimpleRGB(int aWidth, int aHeight) { 
    aRed = new int[aWidth][aHeight]; 
    aBlue = new int[aWidth][aHeight]; 
    aGreen = new int[aWidth][aHeight]; 
} 

/** 
* Gets the width of this image. 
* 
* @return the width of this image. 
*/ 
public int getWidth() { 
    return aWidth; 
} 

/** 
* Gets the height of this image. 
* 
* @return the height of this image. 
*/ 
public int getHeight() { 
    return aHeight; 
} 

/** 
* Sets the red value at coordinate (x,y) to aRed. 
* 
* @param x the x coordinate of this image. 
* @param y the y coordinate of this image. 
* @param aRed the red value (0 - 255) 
*/ 
public void setRed(int x, int y, int aRed) { 
    this.aRed[x][y] = aRed; 
} 

/** 
* Sets the green value at coordinate (x,y) to aGreen. 
* 
* @param x the x coordinate of this image. 
* @param y the y coordinate of this image. 
* @param aGreen the green value (0 - 255) 
*/ 
public void setGreen(int x, int y, int aGreen) { 
    this.aGreen[x][y] = aGreen; 
} 

/** 
* Sets the blue value at coordinate (x,y) to aBlue. 
* 
* @param x the x coordinate of this image. 
* @param y the y coordinate of this image. 
* @param aBlue the blue value (0 - 255) 
*/ 
public void setBlue(int x, int y, int aBlue) { 
    this.aBlue[x][y] = aBlue; 
} 

/** 
* Gets the red value at coordinate (x,y). 
* 
* @param x the x coordinate of this image. 
* @param y the y coordinate of this image. 
* @return the value of red at coordinate (x,y). 
*/ 
public int getRed(int x, int y) { 
    return aRed[x][y]; 
} 

/** 
* Gets the green value at coordinate (x,y). 
* 
* @param x the x coordinate of this image. 
* @param y the y coordinate of this image. 
* @return the value of green at coordinate (x,y). 
*/ 
public int getGreen(int x, int y) { 
    return aGreen[x][y]; 
} 

/** 
* Gets the blue value at coordinate (x,y). 
* 
* @param x the x coordinate of this image. 
* @param y the y coordinate of this image. 
* @return the value of blue at coordinate (x,y). 
*/ 
public int getBlue(int x, int y) { 
    return aBlue[x][y]; 

} 

/** 
* Get the NEW image containing only the red color. The red values of this 
* new image should be exactly the same as red value of this image. The 
* green and blue values of this new image should be 0s. 
* 
* @return the NEW image (SimpleRGB) containing only the red color of this 
* image. 
*/ 
public SimpleRGB getRedImage() { 
    SimpleRGB redImage = new SimpleRGB(aWidth,aHeight); 
    return redImage; 

} 

/** 
* Get the NEW image containing only the green color. The green values of 
* this new image should be exactly the same as green value of this image. 
* The red and blue values of this new image should be 0s. 
* 
* @return the NEW image (SimpleRGB) containing only the green color of this 
* image. 
*/ 
public SimpleRGB getGreenImage() { 
    SimpleRGB greenImage = new SimpleRGB(aWidth,aHeight); 
    return greenImage; 

} 

/** 
* Get the NEW image containing only the blue color. The blue values of this 
* new image should be exactly the same as blue value of this image. The red 
* and green values of this new image should be 0s. 
* 
* @return the NEW image (SimpleRGB) containing only the blue color of this 
* image. 
*/ 
public SimpleRGB getBlueImage() { 
    SimpleRGB blueImage = new SimpleRGB(aWidth,aHeight); 
    return blueImage; 

} 

/** 
* Get the NEW image representing the greyscale of this image. The grey 
* colors are colors that the red, green and blue value are exactly the 
* same. To convert an RGB image into a greyscale image, use the following 
* formula to calculate the new value. (0.21 * red) + (0.72 * green) + (0.07 
* * blue) For example, suppose the (R,G,B) value of this image at 
* coordinate (10,20) are (10,100,200), since (0.21 * 10) + (0.72 * 100) + 
* (0.07 * 200) = 88 the (R,G,B) value of the new greyscale image at (10,20) 
* should be (88,88,88). 
* 
* @return the NEW image representing the greyscale of this image. 
*/ 
public SimpleRGB getGreyImage() { 
    SimpleRGB greyImage = new SimpleRGB(aWidth,aHeight); 
    return greyImage; 

} 

}

+1

Откуда вы знаете? В чем проблема? Как мы можем догадаться, в чем проблема? –

+0

Где находится 'aRed'? Является ли он членом класса, содержащего 'getRedImage()'? –

+0

aRed определяется как двумерный массив, содержащий ширину и высоту, как таковой, aRed = new int [aWidth] [aHeight] ;. Направления говорят, что нужно вернуть новое изображение, но я не знаю, как создать новое изображение в качестве члена класса SimpleRGB – lhenze3

ответ

2

Я хотел бы сделать:

public SimpleRGB getRedImage() { 
    SimpleRGB result = new SimpleRGB(aWidth,aHeight); 
    for (int x = 0; x < aWidth; x++) { 
     for (int y = 0; y < aHeight; y++) { 
      result.setRed(x, y, this.getRed(x, y)); 
     } 
    } 
    return result; 
} 

Это создает новый SimpleRGB изображение с все значения цвета установлен в 0 (по умолчанию все значения в массиве int инициализируются до 0). Затем он устанавливает красное значение этого нового SimpleRGB в соответствие с текущими красными значениями RGB в каждой точке текущего RGB.

+0

это кажется правильным, но я получаю исключение ArrayOutOfBounds на моем getRed(). Какие-либо предложения? – lhenze3

+0

Трудно быть уверенным без дополнительной информации. Но, основываясь только на вашем коде выше (при условии, что он завершен), единственная возможная проблема, которую я замечаю, заключается в том, что ваш конструктор не устанавливает поля aWidth и aHeight, поэтому они будут инициализированы до 0. Это будет означать новый SimpleRGB, который вы создаете в этот метод будет иметь все его массивы с размером 0, то есть у них нет индексов для доступа. Но это также должно остановить работу петель. Независимо от того, попробуйте добавить this.aWidth = aWidth и this.aHeight = aHeight в свой конструктор. Если это не поможет, отправьте свой код и трассировку ошибки. – kmell96

1
public SimpleRGB getRedImage() { 
    SimpleRGB redImage = new SimpleRGB(aWidth, aHeight); 
    for (int x = 0; x < aWidth; ++x) { 
     System.arraycopy(aRed[x], 0, redImage.aRed[x], 0, aHeight); 
    } 
    return redImage; 
} 

Это немедленно использует частные поля напрямую, а метод низкого уровня System.arraycopy - для быстрой копии.

Смежные вопросы