I am wondering is there a way to convert Image to BufferedImage without code like a
new BufferedImage(...)
because every new init makes app run slower, moreover, if it is in paint() method:(
Please advise the most optimal conversion way.
Thanks
No. Not unless the original Image
happens to be a BufferedImage
already. Then you can just do a cast:
BufferedImage bufImg = null;
if (origImage instanceof BufferedImage) {
bufImg = (BufferedImage) origImage;
else {
bugImg = new BufferedImage(...);
// proper initialization
}
If it's not a BufferedImage
it may very well be for instance a VolatileImage
(the other concrete subclass in the API).
From the docs on volatile image:
VolatileImage is an image which can lose its contents at any time due to circumstances beyond the control of the application (eg, situations caused by the operating system or by other applications).
As you may understand, such image can not provide the same interface as a BufferedImage
, thus the only way to get hold of a BufferedImage
is to create one, and draw the original image on top of it.
because every new init makes app run slower
Cache one BufferedImage
, then only create a new image if the required size changes. Otherwise clear the Graphics
object of the current instance and do whatever new drawing is needed.
Is there a way to draw a
BufferedImage
toJLabel
with thepaint()
method?
One convenient approach is to implement the Icon
interface. In this example , Histogram
simply draws itself when the label is told to repaint()
.
If the source of the image requires a time-consuming operation such as scaling, pre-render the image as shown in the static factory, GradientImage
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.