如何直接从内存Bitmap读取字节而非先保存到文件?
从内存Bitmap直接获取字节的实现方案
当然可行!完全不需要先将Bitmap保存到文件再读取字节,直接通过内存流就能搞定。下面给你几种主流编程语言的具体实现方式:
C# (.NET)
在.NET环境中,你可以使用MemoryStream来直接将Bitmap写入内存流,然后提取字节数组:
using System.Drawing; using System.IO; public byte[] BitmapToBytes(Bitmap bitmap) { using (MemoryStream ms = new MemoryStream()) { // 选择你需要的图像格式,比如PNG、JPG等 bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return ms.ToArray(); } }
- 补充:如果是WPF中的
BitmapSource,可以用PngBitmapEncoder来处理:
using System.IO; using System.Windows.Media.Imaging; public byte[] BitmapSourceToBytes(BitmapSource bitmapSource) { byte[] bytes; using (MemoryStream ms = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(ms); bytes = ms.ToArray(); } return bytes; }
Java
在Java中,BufferedImage(对应Bitmap的概念)可以通过ByteArrayOutputStream来转换:
import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import javax.imageio.ImageIO; public byte[] bufferedImageToBytes(BufferedImage image) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 指定输出格式,比如"png"、"jpg" ImageIO.write(image, "png", baos); baos.flush(); byte[] imageBytes = baos.toByteArray(); baos.close(); return imageBytes; }
Python (PIL/Pillow库)
如果你用Python的Pillow库处理图像,Image对象可以直接保存到BytesIO流中:
from PIL import Image import io def image_to_bytes(image): img_byte_arr = io.BytesIO() # 保存时指定格式,比如'PNG'、'JPEG' image.save(img_byte_arr, format='PNG') img_byte_arr.seek(0) # 将指针移到流开头 return img_byte_arr.getvalue()
关键原理
核心思路都是利用内存流(MemoryStream/ByteArrayOutputStream/BytesIO)作为中间载体,将Bitmap/图像对象直接写入内存流,再从流中提取字节数组,全程不会涉及磁盘IO,效率更高。
内容的提问来源于stack exchange,提问作者tmighty
相关产品推荐
相关产品推荐

