问题
I would like to generate an image with just one color on it, to use for creating maps for PhongMaterials. Something like
Image generateImage(int width, int height, double red, double green, double blue, double opacity);
What do I need to do to make this? While I'd prefer to make this purely procedurally, if there's a way to do this by giving it a blank white image like https://dummyimage.com/600x400/ffffff/fff.png and changing its color, I would be okay with that too. I thought about just generating a URL and getting the image directly from that website, but I can't be dependent on internet connection for this to work (and besides, that website doesn't handle transparent images).
回答1:
To return an image as you specify, you can do:
public Image generateImage(int width, int height, double red, double green, double blue, double opacity) {
WritableImage img = new WritableImage(width, height);
PixelWriter pw = img.getPixelWriter();
// Should really verify 0.0 <= red, green, blue, opacity <= 1.0
int alpha = (int) (opacity * 255) ;
int r = (int) (red * 255) ;
int g = (int) (green * 255) ;
int b = (int) (blue * 255) ;
int pixel = (alpha << 24) | (r << 16) | (g << 8) | b ;
int[] pixels = new int[width * height];
Arrays.fill(pixels, pixel);
pw.setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
return img ;
}
In pretty much any use case (that I can think of), you may as well create an image that is 1 pixel by 1 pixel, and then scale it up on the fly. If this suffices, you can simplify this to
public Image generateImage(double red, double green, double blue, double opacity) {
WritableImage img = new WritableImage(1, 1);
PixelWriter pw = img.getPixelWriter();
Color color = Color.color(red, green, blue, opacity);
pw.setColor(0, 0, color);
return img ;
}
Then, e.g. you can do:
Image marshallUniGreen = generateImage(0, 177.0 / 255, 65.0 / 255, 1) ;
ImageView imageView = new ImageView(marshallUniGreen);
imageView.setFitWidth(300);
imageView.setFitHeight(200);
imageView.setPreserveRatio(false);
来源:https://stackoverflow.com/questions/60532986/javafx-generate-blank-single-color-image