我需要创建一个文件,将图像作为文本嵌入到某些记录中.我把图像写成文本时遇到了一些麻烦.我正在做的是从SQL数据库(图像类型)收集图像作为字节数组然后我通过遍历每个字节并将该字节的ASCII等效于文件写入文本文件.
在我将该图像写入文本文件之前,我必须将其转换为CCITT4格式的TIFF(以前是jpeg).为了仔细检查这是否正确完成,我还将流保存为TIFF并在"AsTiffTagViewer"中查看,这表明压缩是正确的.我能够在适当的观众中观看tiff; 但是,从文件中收集文本时,我无法查看图像.
这是代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
正在写入文件的是frontBinary.有没有人知道什么是错的?保存的tiff是正确的,但是当写为ASCII文本时,完全相同的字节数组没有正确写入.
谢谢.
编辑 通过使用BinaryWriter(byte [])将图像正确写入文本已更正此问题.感谢大家的帮助!
Jon*_*eet 17
一方面,ASCII只有七位.但是,我不相信您的代码实际上使用ASCII.它隐含地使用ISO-8859-1.
永远不要将文本视为二进制,反之亦然.它总会导致问题.
将二进制文件转换为ASCII文本的最佳方法是使用Base64:
string text = Convert.ToBase64String(frontImage);
byte[] data = Convert.FromBaseString(text);
Run Code Online (Sandbox Code Playgroud)
另请注意,如果您的代码确实有效,那么它仍然会非常低效 - 请阅读StringBuilders,然后考虑您的代码是半等效的
Encoding.GetEncoding(28591).GetString(data);
Run Code Online (Sandbox Code Playgroud)
但是,base64绝对是无损地在文本和二进制数据之间进行转换的方法.当然,您需要将其转换回二进制才能再次查看TIFF.
请注意,您尚未显示如何保存或加载数据 - 您也可能遇到问题.事实上,我怀疑如果你能够准确地保存字符串,你可能很幸运并保留了数据,具体取决于你正在做什么......但是无论如何都要使用base64.
归档时间: |
|
查看次数: |
14082 次 |
最近记录: |