簡體   English   中英

將圖像轉換為字節數組的最快方法

[英]Fastest way to convert Image to Byte array

我正在制作遠程桌面共享應用程序,我在其中捕獲桌面圖像並將其壓縮並將其發送給接收者。 要壓縮圖像,我需要將其轉換為 byte[]。

目前我正在使用這個:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return  ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

但我不喜歡它,因為我必須將它保存在 ImageFormat 中,這也可能會耗盡資源(減速)並產生不同的壓縮結果。我已經閱讀過使用 Marshal.Copy 和 memcpy 但我無法理解他們。

那么有沒有其他方法可以達到這個目的呢?

Image參數的RawFormat屬性返回圖像的文件格式。 您可以嘗試以下方法:

// extension method
public static byte[] imageToByteArray(this System.Drawing.Image image)
{
    using(var ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        return ms.ToArray();
    }
}

那么有沒有其他方法來實現這一目標?

不能。為了將圖像轉換為字節數組,您必須指定圖像格式 - 就像在將文本轉換為字節數組時必須指定編碼一樣。

如果您擔心壓縮文物,請選擇無損格式。 如果您擔心CPU資源,請選擇一種不打擾壓縮的格式 - 例如,原始ARGB像素。 但當然這將導致更大的字節數組。

請注意,如果你選擇一個格式包括壓縮,有一個在事后再壓縮字節數組是沒有意義的-這是幾乎可以肯定有沒有益處。

我不確定你是否會因為Jon Skeet指出的原因獲得任何巨大收益。 但是,您可以嘗試對TypeConvert.ConvertTo方法進行基准測試,並查看它與使用當前方法的比較。

ImageConverter converter = new ImageConverter();
byte[] imgArray = (byte[])converter.ConvertTo(imageIn, typeof(byte[]));
public static byte[] ReadImageFile(string imageLocation)
    {
        byte[] imageData = null;
        FileInfo fileInfo = new FileInfo(imageLocation);
        long imageFileLength = fileInfo.Length;
        FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        imageData = br.ReadBytes((int)imageFileLength);
        return imageData;
    }
public static class HelperExtensions
{
    //Convert Image to byte[] array:
    public static byte[] ToByteArray(this Image imageIn)
    {
        var ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }

    //Convert byte[] array to Image:
    public static Image ToImage(this byte[] byteArrayIn)
    {
        var ms = new MemoryStream(byteArrayIn);
        var returnImage = Image.FromStream(ms);
        return returnImage;
    }
}

我能找到的最快方法是:

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

希望有用

嘗試以下代碼:

public Byte[] ConvertPictureToByte(System.Drawing.Image PictureFile)
{
   using (var MemStrm = new MemoryStream())
   {
      PictureFile.Save(MemStrm,PictureFile.RawFormat);
      return  MemStrm.ToArray();
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM