对于小于16*16=256的图像是一定可以用图像深度8来表示,因为图像深度8可以表示256种不同点,16*16就是256个点,所有点不一样都可以表示。
例子中给出了转化的方法,同时考虑了透明像素点的问题。
例子中限定了传入的图像一定是16*16,保证可以转,实际上更一般的情况是少于256个情况,直接转多余的话,找相近的点,不过那样的话选取哪256RGB点就比较的要有技巧了。
例子:
public class ImageSize {
public static ImageData image16or24or32_to8depth(ImageData orgData) {
if(orgData.width != 16 || orgData.height != 16)
throw new IllegalArgumentException("Want width and height is 16, but width is "+
orgData.width + "and height is " + orgData.height + ".");
printImageDataInfo(orgData);
List<RGB> list = new ArrayList<RGB>();
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
RGB rgb;
for(int h=0; h<16; h++) {
for(int w=0; w<16; w++) {
rgb = orgData.palette.getRGB(orgData.getPixel(w, h));
if(!list.contains(rgb)) {
list.add(rgb);
map.put(h*16+w, list.size()-1);
} else {
map.put(h*16+w, list.indexOf(rgb));
}
}
}
PaletteData paletteData = new PaletteData(list.toArray(new RGB[0]));
ImageData newData = new ImageData(16,16,8,paletteData);
for(int h=0; h<16; h++) {
for(int w=0; w<16; w++) {
newData.setPixel(w, h, map.get(h*16+w));
}
}
newData.transparentPixel = list.indexOf(orgData.palette.getRGB(orgData.transparentPixel));
printImageDataInfo(newData);
return newData;
}
private static void printImageDataInfo(ImageData imageData) {
System.out.println(imageData);
System.out.printf("%-15s : %d %n","width",imageData.width);
System.out.printf("%-15s : %d %n","height",imageData.height);
System.out.printf("%-15s : %d %n","depth",imageData.depth);
System.out.printf("%-15s : %d %n","bytesPerLine",imageData.bytesPerLine);
System.out.printf("%-15s : %d %n","data.length",imageData.data.length);
}
public static void main(String[] args) {
String saved = "icons/ZZ_save.gif";
String source = "icons/ZZ_source.gif";
ImageData[] imageData = ImageUtil.readImage(source);
if(imageData.length > 0) {
ImageData data = imageData[0];
ImageUtil.saveImage(saved, new ImageData[]{image16or24or32_to8depth(data)}, SWT.IMAGE_PNG);
}
}
}
主要函数:image16or24or32_to8depth。