Java : BufferedImage 到 Bitmap 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6331068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java : BufferedImage to Bitmap format
提问by Anand S Kumar
I have a program in which i capture the screen using the code :
我有一个程序,我在其中使用代码捕获屏幕:
robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
Now i want to convert this BufferedImage into Bitmap format and return it through a function for some other need, Not save it in a file. Any help please??
现在我想将此 BufferedImage 转换为 Bitmap 格式并通过函数返回它以满足其他一些需要,而不是将其保存在文件中。请问有什么帮助吗??
采纳答案by aioobe
You need to have a look at ImageIO.write
.
你需要看看ImageIO.write
。
If you want the result in the form of a byte[]
array, you should use a ByteArrayOutputStream
:
如果你想要byte[]
数组形式的结果,你应该使用ByteArrayOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(yourImage, "bmp", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
回答by Ninto
When you say "into Bitmap format" you then mean the data (as in a byte array)? If that's the case, then you can use ImageIO.write
(like suggested above).
If you don't want to save it to a file, but just want to get the data, can you use a ByteArrayOutputStream
like this:
当您说“进入位图格式”时,您的意思是数据(如字节数组)?如果是这种情况,那么您可以使用ImageIO.write
(如上面建议的那样)。
如果您不想将其保存到文件,而只想获取数据,您可以使用ByteArrayOutputStream
这样的:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(img, "BMP", out);
byte[] result = out.toByteArray();
回答by Andrew Thompson
To see the image types available for write in the J2SE (ex. JAI), see ImageIO.getWriterFileSuffixes()
:
要查看可在 J2SE 中写入的图像类型(例如 JAI),请参阅ImageIO.getWriterFileSuffixes()
:
E.G.
例如
class ShowJavaImageTypes {
public static void main(String[] args) {
String[] imageTypes =
javax.imageio.ImageIO.getWriterFileSuffixes();
for (String imageType : imageTypes) {
System.out.println(imageType);
}
}
}
Output
输出
For this Sun Java 6 JRE on Windows 7.
对于 Windows 7 上的此 Sun Java 6 JRE。
bmp
jpg
wbmp
jpeg
png
gif
Press any key to continue . . .
See similar ImageIO
methods for MIME types, formats, and the corresponding readers.
请参阅ImageIO
MIME 类型、格式和相应阅读器的类似方法。
回答by Raul Lucaciu
You can simply do this:
你可以简单地这样做:
public Bitmap getBitmapFromBufferedImage(BufferedImage image)
{
return redResult.getBitmap();
}