将位图数据保存为纯文本

时间:2013-07-10 10:08:59

标签: c# .net bitmap text-files

我正在寻找一种用C#将一堆小图像保存到一个(文本)文件中的方法。

我正在考虑使用2D循环(2个嵌套for循环)获取像素数据(rgb值)并将其作为字符串写入文件。

有更优雅的方法吗?也许保存为十六进制颜色或uint? (#FF00FF / 0xFF00FF)

我如何构建最终的文本文件,以便以后阅读(我想用自定义算法加密文本文件)。

2 个答案:

答案 0 :(得分:3)

您可以将图片打开为二进制并将其转换为Base64,然后您可以将其作为字符串保存到文本文件中。

    public static string CreateFileStringFromPath(string tempPath)
    {
        //We Convert The Image into a BASE64 String and so store it as text
        //First we add a Stream to the File
        FileStream tempStream = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
        try
        {
            //Then we write the Stream to a Byte Array
            byte[] tempByteArray = ReadStreamFully(tempStream);
            tempStream.Dispose();
        }
        catch(Exception)
        {
            tempStream.Dispose();
            return null;
        }

        //Then we Convert the Byte Array to a Base64 String and return it
        return Convert.ToBase64String(tempByteArray);
    }

    public static byte[] ReadStreamFully(Stream tempFileStreamInput)
    {
        //We Create a MemoryStream which we can form into an Byte Array
        using(MemoryStream tempMemoryStream = new MemoryStream())
        {
            tempFileStreamInput.CopyTo(tempMemoryStream);
            return tempMemoryStream.ToArray();
        }
    }

既然我们有一个String,我们只需要一种方法来存储它们,因为你想将它们存储在磁盘上考虑XML(可能是XSD样式表)或者将它们插入任何其他可串行的结构,如JSON

编辑1:根据要求,这是一种保存像素的方法

private Color[,] GetPixel_Example(Bitmap myBitmap)
{
Color[,] tempColor = new Color[myBitmap.width,myBitmap.height]
for(int i = 0; i < myBitmap.height;i++)
  for(int j = 0; j < myBitmap.width;j++)
    // Get the color of a pixel within myBitmap.
    Color pixelColor = myBitmap.GetPixel(j,i);
    //And save it in the array
    tempColor[j,i] = pixelColor;
return tempColor;
}

这个例子自然只适用于Bitmaps并返回一个二维数组,其中所有像素都保存为Color,现在可以提取RGB或HEX等等。您可以轻松地将示例更改为System.Media.Images或仅文件。如果您不知道如何将图片制作成位图,应该有类似Bitmap.LoadFromFile();

答案 1 :(得分:0)

因为你有多个图像。做结构化文件,比如说xml e.g。

<Images>
 <Image name = "somename.someimageextension"
 <Content></Content>
</Image>
</Images>

要获取内容,请将您的图像(从磁盘?)作为流,将其转换为base64,如

string contentAsBase64 = Convert.ToBase64String(imageAsStream.ToArray());

加密/签署整个文档。