将原始 RGB 字节数组转换为 JPG 编码的字符串 base64

Convert a raw RGB byte array to a JPG encoded string base64

我成功地将 JPG 图像文件转换为 base64 字符串,然后将该字符串再次转换为 JPG 图像。

string str64 = ImageToStrBase64(My.Resources.ImageJpg);
PictureBox1.Image = Base64StrToImage(str64);

ImageToStrBase64()Base64StrToImage()是自定义函数,只是为了说明思路,如果有需要我可以放代码

我还将原始字节数组(RGB 或 BGR,无所谓)转换为 base64。

但是,我现在确实需要将原始字节数组转换为 JPG 编码的 base64 字符串。我正在寻找仅涉及图像文件保存的解决方案,但文件管理非常耗时。如何使用例如内存流将 BGR 字节数组编码为 JPG 字节数组?

将jpg转换为格式化字节数组的函数:

public static string ImagetoStrBase64(System.Drawing.Image imageToEncode)
{
    string base64String = "";

    using (System.Drawing.Image image = imageToEncode)
    {
        using (MemoryStream m = new MemoryStream())
        {
            image.Save(m, image.RawFormat);
            byte[] imageBytes = m.ToArray();
            base64String = Convert.ToBase64String(imageBytes);
        }
    }

    return base64String;
}

更新(关于chat

让我们简化它...我们有一个 byte[] 具有单个绿色像素:

byte[] rawPixelArray = new byte[] {0, 255, 0}; 

然后,GetJpgBytes(rawPixelArray) 必须 return 编码 byte[] 用于 1x1 像素的 Jpeg 图像。我想这更清楚了:)

Before you read the answer, read the bullet points:

  • A real useful conversion, should return JPEG encoded image which is equivalent to content of a Jpeg file, which is not pixel data.

  • When you get an array of pixel data of a Jpeg image, you will have non of benefits of a Jpeg image. It's no more Jpeg encoded image, it's an array of pixel data which can be used to create a BitMap.

  • To better understand the point, for example for a 10K JPEG white image, the pixel data will be 2MB!

  • I've shared a few methods in this answer which are really useful standalone, and I've showed how you can combine them to get what you want. (While I cannot see any benefit in the conversion which you are trying to do.)


这些是非常有用的部分,您可以将它们放在一起来解决难题:

  1. ImageData:除了byte[]的图片像素,你还需要了解图片的宽高和像素格式。然后您可以描述图像并根据该数据创建 Image。如果没有所有这些信息,byte[] 本身就毫无意义。
  2. GetImageDataFromImage:从Image
  3. 获取图像数据(宽度、高度、像素格式、像素数据)
  4. CreateImageFromImageData:从图像数据
  5. 创建Image
  6. ConvertImageToJpegImage:将 Image 转换为 Jpeg Image
  7. ByteArrayToBase64:将 byte[] 转换为 Base64 字符串。

那么有了这些之后,你就可以实现你想要的了。

假设您有 byte[] 像素数据、数据的宽度、高度和像素格式,这就是您需要的:

// A 2x2 image having 24 bit RGB pixel format, all pixels are #FF0000 (Red)
var imageData = new ImageData()
{
    Width = 2,
    Height = 2,
    PixelFormat = PixelFormat.Format24bppRgb,
    PixelData = new byte[] {
        0x0, 0x0, 0xFF,   0x0, 0x0, 0xFF,
        0xF, 0x0, 0xFF,   0x0, 0x0, 0xFF
    }
};
var image = CreateImageFromImageData(imageData);
var jpeg = ConvertImageToJpegImage(image);
var jpegImageData = GetImageDataFromImage(jpeg);
var jpegPixelsBase64 = ByteArrayToBase64(jpegImageData.PixelData);

这导致 AAD+AAD+AAD+AAD+ 实际上是具有 #FE0000 颜色的图像!

Note: I didn't dispose images to keep it clear, in action, you need to dispose image and jpeg.

ImageData

有关图像的必需信息,包括宽度、高度、像素格式和像素数据数组:

public class ImageData
{
    public int Width { get; set; }
    public int Height { get; set; }
    public PixelFormat PixelFormat { get; set; }
    public byte[] PixelData { get; set; }
}

GetImageDataFromImage

从图像中获取图像数据。

ImageData GetImageDataFromImage(Image image)
{
    using (var bitmap = new Bitmap(image.Width, image.Height, image.PixelFormat))
    {
        using (var g = Graphics.FromImage(bitmap))
            g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
        var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
            ImageLockMode.ReadOnly, bitmap.PixelFormat);
        var rowLength = image.Width * Image.GetPixelFormatSize(image.PixelFormat) / 8;
        var bytes = new byte[image.Height * rowLength];
        var ptr = data.Scan0;
        for (var i = 0; i < image.Height; i++)
        {
            Marshal.Copy(ptr, bytes, i * rowLength, rowLength);
            ptr += data.Stride;
        }
        bitmap.UnlockBits(data);
        return new ImageData
        {
            Width = bitmap.Width,
            Height = bitmap.Height,
            PixelFormat = bitmap.PixelFormat,
            PixelData = bytes
        };
    }
}

我们依靠LockBits来获取或设置图像字节数组。

CreateImageFromImageData

从图像数据创建图像:

Image CreateImageFromImageData(ImageData imageData)
{
    var bitmap = new Bitmap(imageData.Width, imageData.Height, imageData.PixelFormat);
    var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.ReadWrite, bitmap.PixelFormat);
    var rowLength = imageData.Width * Image.GetPixelFormatSize(imageData.PixelFormat) / 8;
    var bytes = new byte[imageData.Height * rowLength];
    var ptr = data.Scan0;
    for (var i = 0; i < imageData.Height; i++)
    {
        Marshal.Copy(imageData.PixelData, i * rowLength, ptr, rowLength);
        ptr += data.Stride;
    }
    bitmap.UnlockBits(data);
    return bitmap;
}

我们依靠LockBits来获取或设置图像字节数组。

ConvertImageToJpegImage

将图像转换为 Jpeg 图像:

public Image ConvertImageToJpegImage(Image img)
{
    using (var stream = new MemoryStream())
    {
        img.Save(stream, ImageFormat.Jpeg);
        var bytes = stream.ToArray();
        return (Image)new ImageConverter().ConvertFrom(bytes);
    }
}

如果您关心压缩级别,请使用 jpeg encoder

ByteArrayToBase64

byte[]Base64String 的转换很简单,但为了更好地阅读答案和代码:

public string ByteArrayToBase64(byte[] bytes)
{
    return Convert.ToBase64String(bytes);
}