将图像作为二进制数据写入文本文件 C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/885237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:20:18  来源:igfitidea点击:

Writing an image to a text file as binary data C#

c#imagestream

提问by Aaron

I need to create a file that embeds an image as text within some records. I'm having some trouble writing the images as text. What I'm doing is gathering the image as a byte array from a SQL database (image type) then I'm writing that image to a text file by going through each byte and writing that byte's ASCII equivalent to the file.

我需要创建一个文件,将图像作为文本嵌入某些记录中。我在将图像编写为文本时遇到了一些麻烦。我正在做的是从 SQL 数据库(图像类型)中将图像作为字节数组收集,然后通过遍历每个字节并将该字节的 ASCII 等效于该文件,将该图像写入文本文件。

Before I can write that image to a text file, I must convert it to a TIFF (it was formerly a jpeg) in CCITT4 format. To double check that this is being done correctly, I also save the stream as a TIFF and view it in "AsTiffTagViewer," which shows that the compression is correct. I AM able to view the tiff in a proper viewer; however, when gathering the text from the file, I am unable to view the image.

在将该图像写入文本文件之前,我必须将其转换为 CCITT4 格式的 TIFF(以前是 jpeg)。为了仔细检查这是否正确完成,我还将流保存为 TIFF 并在“AsTiffTagViewer”中查看它,这表明压缩是正确的。我能够在适当的查看器中查看 tiff;但是,从文件中收集文本时,我无法查看图像。

Here's the code:

这是代码:

byte[] frontImage = (byte[])imageReader["front_image"];
MemoryStream frontMS = new MemoryStream(frontImage);
Image front = Image.FromStream(frontMS);
Bitmap frontBitmap = new Bitmap(front);
Bitmap bwFront = ConvertToBitonal(frontBitmap);
bwFront.SetResolution(200, 200);
MemoryStream newFrontMS = new MemoryStream();
bwFront.Save(newFrontMS, ici, ep);
bwFront.Save("c:\Users\aarong\Desktop\C#DepositFiles\" + checkReader["image_id"].ToString() + "f.tiff", ici, ep);
frontImage = newFrontMS.ToArray();   
String frontBinary = toASCII(frontImage); 

private String toASCII(byte[] image)
{
    String returnValue = "";
    foreach (byte imageByte in image)
    {
        returnValue += Convert.ToChar(imageByte);
    }
    return returnValue;
}   

It is frontBinary that's being written to the file. Does anyone have an idea as to what is wrong? The tiff that's saved is correct, yet the exact same byte array, when written as ASCII text, is not being written correctly.

正在写入文件的是frontBinary。有没有人知道什么是错的?保存的 tiff 是正确的,但完全相同的字节数组,当写为 ASCII 文本时,没有被正确写入。

Thank you.

谢谢你。

EDITThis issue has been corrected by using a BinaryWriter(byte[]) to correctly write the images as text. Thank you all for your help!

编辑此问题已通过使用 BinaryWriter(byte[]) 将图像正确写入文本而得到纠正。谢谢大家的帮助!

采纳答案by Jon Skeet

Well ASCII is only seven-bit, for one thing. However, I don't believe your code actually uses ASCII. It sort of uses ISO-8859-1, implicitly.

一方面,ASCII 只有七位。但是,我不相信您的代码实际上使用 ASCII。它隐含地使用了 ISO-8859-1。

Nevertreat text as binary or vice versa. It will alwayslead to problems.

切勿将文本视为二进制,反之亦然。它总是会导致问题。

The best way of converting binary to ASCII text is to use Base64:

将二进制转换为 ASCII 文本的最佳方法是使用 Base64:

string text = Convert.ToBase64String(frontImage);
byte[] data = Convert.FromBaseString(text);

Also note that if your code didwork, it would still be painfully inefficient - read up on StringBuildersand then consider that your code is semi-equivalent to

另请注意,如果您的代码确实有效,它仍然会非常低效 - 阅读StringBuilders,然后考虑您的代码半等效于

Encoding.GetEncoding(28591).GetString(data);

However, base64 is definitely the way to go to convert between text and binary data losslessly. You'll need to convert it back to binary in order to view the TIFF again, of course.

但是,base64 绝对是在文本和二进制数据之间无损转换的方法。当然,您需要将其转换回二进制以便再次查看 TIFF。

Note that you haven't shown how you're saving or loading your data - you may have problems there too. In fact, I suspect that if you were able to save the string accurately, you mighthave been lucky and preserved the data, depending on exactly what you're doing with it... but go with base64 anyway.

请注意,您尚未显示如何保存或加载数据 - 您可能也有问题。事实上,我怀疑如果您能够准确地保存字符串,那么您可能很幸运并保留了数据,具体取决于您正在使用它做什么……但无论如何都要使用 base64。

回答by Will Charczuk

One approach to taking binary data and converting it to text data is to use a StreamReader and provide the desired encoding. Like Jon mentioned above it is unwise to use ASCII, but in case any one DOES want to stream binary to some other text encoding, here is some code to do it.

获取二进制数据并将其转换为文本数据的一种方法是使用 StreamReader 并提供所需的编码。就像上面提到的 Jon 一样,使用 ASCII 是不明智的,但是如果有人想将二进制流传输到其他文本编码,这里有一些代码可以做到。

public static String GetString(System.IO.Stream inStream)
{
    string str = string.Empty;
    using (StreamReader reader = new StreamReader(inStream, System.Text.ASCIIEncoding.ASCII)) // or any other encoding.
    {
        str = reader.ReadToEnd();
    }
    return str;
}

回答by codymanix

Is there a specific reason why you use text instead of a binary file?

使用文本而不是二进制文件有什么具体原因吗?

Storing binary data in text files is always a bad idea since encodings may convert the bytes to another representation and special characters like linefeed may also be treated specially and converted.

将二进制数据存储在文本文件中总是一个坏主意,因为编码可能会将字节转换为另一种表示形式,并且换行等特殊字符也可能被特殊处理和转换。

Either store the data as byte array in a binary file or use proper binary to ascii conversion like Jon's Base64 proposal or maybe a list of comma separated hex-values is also possible.

要么将数据作为字节数组存储在二进制文件中,要么使用适当的二进制到 ascii 转换,如 Jon 的 Base64 提议,或者也可以使用逗号分隔的十六进制值列表。

回答by Guffa

If you are writing only the image data to the file, you should not write it as text at all, but as binary data.

如果您只将图像数据写入文件,则根本不应将其写为文本,而应将其写为二进制数据。

If you are mixing text and binary data in the file, you should not convert the binary data to text. It might work with some specific encodings to convert it back and forth, but it certainly doesn't work with any encoding to convert it to unicode characters (using Convert.ToChar).

如果在文件中混合文本和二进制数据,则不应将二进制数据转换为文本。它可能适用于某些特定的编码来来回转换,但它肯定不适用于将其转换为 unicode 字符的任何编码(使用Convert.ToChar)。

Do it the other way around. Encode the text into binary data using the GetBytesmethod of the proper Encodingobject, so that you only have binary data to write to the file.

反过来做。使用GetBytes适当Encoding对象的方法将文本编码为二进制数据,以便您只有二进制数据可以写入文件。

回答by Adam Says - Reinstate Monica

You're probably reading the database back as Unicode, which will alter some of the binary values in the image.

您可能正在将数据库读回 Unicode,这将改变图像中的一些二进制值。

You can use methods on the System.IO.File class to read/save as binary and text. These might help along with the Base64 options mentioned above.

您可以使用 System.IO.File 类上的方法来读取/保存为二进制和文本。这些可能有助于上述 Base64 选项。