이미지를 BufferedImage로 변환하는 Java
이미이 링크 와 같은 질문이 StackOverflow에 있으며 허용되는 답변은 "casting"입니다.
Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;
내 프로그램에서 다음을 시도합니다.
final float FACTOR = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = (BufferedImage) image;
불행하게도 런타임 오류가 발생합니다.
sun.awt.image.ToolkitImage를 java.awt.image.BufferedImage로 캐스트 할 수 없습니다.
분명히 캐스팅이 작동하지 않습니다.
질문 : Image를 BufferedImage로 변환하는 적절한 방법은 무엇입니까 (또는 거기에 있습니까)?
A로부터 자바 게임 엔진 :
/**
* Converts a given Image into a BufferedImage
*
* @param img The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
이를 처리하는 한 가지 방법은 새로운 BufferedImage를 생성하고 그래픽 객체에게 스케일링 된 이미지를 새로운 BufferedImage에 그리도록 지시하는 것입니다.
final float FACTOR = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);
그것은 캐스팅하지 않고 트릭을 수행해야합니다.
를 다시 가져 오는 경우 sun.awt.image.ToolkitImage
Image를 해당 이미지로 캐스팅 한 다음 getBufferedImage () 를 사용 하여 BufferedImage
.
So instead of your last line of code where you are casting you would just do:
BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();
If you use Kotlin, you can add an extension method to Image in the same manner Sri Harsha Chilakapati suggests.
fun Image.toBufferedImage(): BufferedImage {
if (this is BufferedImage) {
return this
}
val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB)
val graphics2D = bufferedImage.createGraphics()
graphics2D.drawImage(this, 0, 0, null)
graphics2D.dispose()
return bufferedImage
}
And use it like this:
myImage.toBufferedImage()
참고URL : https://stackoverflow.com/questions/13605248/java-converting-image-to-bufferedimage
'Programing' 카테고리의 다른 글
Xcode : 헤더 복사 : 공개 vs. 비공개 vs. 프로젝트? (0) | 2020.11.08 |
---|---|
플렉스 아이템이 텍스트로 인해 넘치지 않게하는 방법은 무엇입니까? (0) | 2020.11.08 |
텍스트를 왼쪽으로 90도 회전하는 방법 및 셀 크기는 html의 텍스트에 따라 조정됩니다. (0) | 2020.11.08 |
JWT와 Bearer Token의 차이점은 무엇입니까? (0) | 2020.11.08 |
기능적 프로그래밍 및 비 기능적 프로그래밍 (0) | 2020.11.08 |