![](/img/trans.png)
[英]How to convert BufferedImage(RGB) to BufferedImage(ARGB or RGBA)?
[英]How to convert BufferedImage RGBA to BufferedImage RGB?
因此,我嘗試尋找解決方案,但找不到可以將RGBA
轉換為RGB
格式的解決方案。
如果給出了從BufferedImage到BufferedImage轉換的簡單解決方案,那將是最好的,否則問題如下:
基本上我必須將BufferedImage轉換為MAT
格式。 它適用於JPG / JPEG圖像,但不適用於PNG。 以下代碼用於轉換::
BufferedImage biImg = ImageIO.read(new File(imgSource));
mat = new Mat(biImg.getHeight(), biImg.getWidth(),CvType.CV_8UC3);
Imgproc.cvtColor(mat,matBGR, Imgproc.COLOR_RGBA2BGR);
byte[] data = ((DataBufferByte) biImg.getRaster().getDataBuffer()).getData();
matBGR.put(0, 0, data);
這會對具有RGBA值的圖像引發錯誤。 因此尋求解決方案。
提前致謝。
我找到了這樣的解決方案:
BufferedImage oldRGBA= null;
try {
oldRGBA= ImageIO.read(new URL("http://yusufcakmak.com/wp-content/uploads/2015/01/java_ee.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final int width = 1200;
final int height = 800;
BufferedImage newRGB = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
newRGB .createGraphics().drawImage(oldRGBA, 0, 0, width, height, null);
try {
ImageIO.write(newRGB , "PNG", new File("your path"));
} catch (IOException e) {}
因此,在這里,當我們創建新的BufferedImage
,可以使用以下方式更改圖像的類型:
RGB與PNG一起為我工作。
public static BufferedImage toBufferedImageOfType(BufferedImage original, int type) {
if (original == null) {
throw new IllegalArgumentException("original == null");
}
if (original.getType() == type) {
return original;
}
BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type);
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(original, 0, 0, null);
}
finally {
g.dispose();
}
return image;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.