C# - 图像的高质量字节数组转换

时间:2010-06-17 20:01:01

标签: c#

我正在使用以下代码将图像转换为字节数组并存储在文本文件中。我也成功地检索了它们。

我担心的是检索图像的质量达不到预期。有没有办法更好地转换为字节数组并检索?我并不担心空间概念。

请分享您的想法。

    string plaintextStoringLocation = @"D:\ImageSource\Cha5.txt";
    string bmpSourceLocation = @"D:\ImageSource\Cha50.bmp";

    ////Read image
    Image sourceImg = Image.FromFile(bmpSourceLocation);

    ////Convert to Byte[]
    byte[] clearByteArray = ImageToByteArray(sourceImg);


    ////Store it for future use (in plain text form)
    StoreToLocation(clearByteArray, plaintextStoringLocation);

    //Read from binary
    byte[] retirevedImageBytes = ReadByteArrayFromFile(plaintextStoringLocation);

    //Retrieve from Byte[]
    Image destinationImg = ByteArrayToImage(retirevedImageBytes);

    //Display Image
    pictureBox1.Image = destinationImg;

编辑:解决方法是 - 使用Base64

            //Plain Text Storing Location
            string plaintextStoringLocation = @"D:\ImageSource\GirlInflower23.txt";
            string bmpSourceLocation = @"D:\ImageSource\GirlInflower1.bmp";

            ////Read image
            Image sourceImg = Image.FromFile(bmpSourceLocation);


            string base64StringOfIMage = ImageToBase64(sourceImg, ImageFormat.Bmp);

            byte[] byteOfString = Convert.FromBase64String(base64StringOfIMage);


            StoreToLocation(byteOfString, plaintextStoringLocation);

            byte[] retrievedBytesForStrimngForImage = ReadByteArrayFromFile(plaintextStoringLocation);


            MemoryStream memStream = new MemoryStream(retrievedBytesForStrimngForImage);
            //memStream.Read();

            Image retrievedImg = Image.FromStream(memStream);
            pictureBox1.Image = retrievedImg;

2 个答案:

答案 0 :(得分:2)

是的,可以获得完全无损的存储空间。如果您只是以原始的BMP格式存储它将没有问题。我假设您正在将其转换为文本,因为您希望通过某些协议发送它,其中二进制字符将被破坏。

您可以考虑使用Convert.ToBase64String

而不是您正在做的任何事情

答案 1 :(得分:1)

我对这个片段没有任何问题...尝试一下......如果你得到了好的结果,那么问题出在你的图片中 - > byte []或byte [] - >图片代码:)

Image srcImage;
Image destImage;

// load an image
srcImage = Image.FromFile(filename);

// save the image via stream -> byte[]
using(MemoryStream stream = new MemoryStream()){
   image.Save(stream, ImageFormat.xxx);
   byte[] saveArray = stream.ToArray();
   /*..... strore saveArray......*/
}

// rehydrate
byte[] loadArray = /*...get byte array from storage...*/

using(MemoryStream stream = new MemeoryStream(loadArray)){
  destImage = Image.FromStream(stream);
}

pictureBox.Image = dstImage;

// don't forget...dispose of any Image/Stream objects