[0,255]의 값을 포함 하는 배열 int[] shadesOfGray
크기 n*n
가 있습니다. 이 배열에서 8 비트 회색조 비트 맵을 만들 수 있습니까?
예 : int[] shadesOfGray = {255, 255, 255, 128, 128, 128, 0, 0, 0}
그러면 비트 맵에서 해당 픽셀의 강도는 다음과 같습니다.
255 255 255
128 128 128
0 0 0
나는 다음과 같은 것을 시도했다.
private static void generateBMPwithDistribution(int[] shadesOfGray, int sum, String path) throws IOException {
int dim = 100;
byte[] buffer = new byte[dim * dim];
for (int x = 0, i = 0; x < dim; x++)
for (int y = 0; y < dim; y++)
buffer[(x * dim) + y] = (byte) (shadesOfGray[i]); // problem
try {
ImageIO.write(getGrayscale(dim, buffer), "bmp", new File(path));
} catch (IOException e) {
...
}
}
public static BufferedImage getGrayscale(int width, byte[] buffer) {
int height = buffer.length / width;
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
int[] nBits = { 8 };
ColorModel cm = new ComponentColorModel(cs, nBits, false, true,
Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
SampleModel sm = cm.createCompatibleSampleModel(width, height);
DataBufferByte db = new DataBufferByte(buffer, buffer.length);
WritableRaster raster = Raster.createWritableRaster(sm, db, null);
BufferedImage result = new BufferedImage(cm, raster, false, null);
return result;
}
8 비트 .bmp를 원하기 때문에 버퍼의 값을 복사 한 다음 버퍼를 파일에 씁니다. 문제는 값> = 128입니다. 바이트는 음수 값으로 간주됩니다. 이것을 극복하는 방법이 Java에 있습니까?
절차는 다음과 같을 수 있습니다.
private static void generateBMPwithDistribution(int[] shadesOfGray, int sum, String path) throws IOException {
int dim1 = (int)Math.sqrt(shadesOfGray.length), dim=100*dim1;
int[] buffer = new int[dim * dim];
int howManyTimes=dim/dim1;
for (int x = 0; x < dim; x++)
for (int y = 0; y < dim; y++) {
int valueToReplicate=shadesOfGray[(x + y*dim)/howManyTimes];
buffer[x + y*dim] = 0xff000000|(valueToReplicate<<16)|(valueToReplicate<<8)|valueToReplicate;
}
BufferedImage result=new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB);
try {
ImageIO.write(result, "bmp", new File(path));
} catch (IOException e) {
...
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다