将“PDF”解压缩的GZipStream转换为“PNG”C#
问题描述:
我要求从亚马逊运输标签,他们发回一个字符串是一个压缩的“GZIP”文件,我必须将其保存为“.gz”扩展名然后我可以对其进行解压缩(或解压缩),有时是“PNG”格式的字符串,有些是“PDF”格式! 但我希望每次都以“PNG”格式打印,但当他们发回“PDF”格式时,我无法将解压缩(GZIPSTREAM)文件转换为“PNG”! 有没有安装第三方库的帮助?将“PDF”解压缩的GZipStream转换为“PNG”C#
这里是我的代码
public async Task PrintLabel(string imageLabelString)
{
var byteStream = Convert.FromBase64String(imageLabelString);
GZipStream gzip = null;
Image image = null;
using (MemoryStream memoryStream = new MemoryStream(byteStream))
{
image = null;
//File.WriteAllBytes("temp.gz", byteStream);
using (gzip = new GZipStream(memoryStream, CompressionMode.Decompress))
{
image = Image.FromStream(gzip);
};
memoryStream.Position = 0;
image.RotateFlip(RotateFlipType.Rotate90FlipNone);
PrintDocument pd = new PrintDocument();
pd.PrintPage += (object o, PrintPageEventArgs e) =>
{
Rectangle rectangle = new Rectangle(0, 0, 500, 750);
e.Graphics.DrawImage(image, rectangle);
};
pd.PrinterSettings.PrinterName = "PrinterName";
pd.Print();
}
this.Close();
}
答
您可以通过查看前4个字节流的检测PNG。 PNG有一个可以很容易检测到的标记。
bool IsStreamPng(Stream s)
{
s.Seek(0, SeekOrigin.Begin); //Go to the start of the stream
var headerBytes = new byte[4]; //Create a buffer to hold 4 bytes of data
s.Read(headerBytes, 0, 4); //Copy 4 bytes of data to the buffer
var headerString = Encoding.ASCII.GetString(headerBytes); //convert the buffer to a string
return headerString.ToUpper().EndsWith("PNG"); //do the first 4 characters of the header end with "PNG"?
}
答
...是改进@布拉德利的解决方案,以避免不必要的分配:
从http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html
第8个字节的PNG文件始终包含以下(十进制)值:
137 80 78 71 13 10 26 10
public static Boolean IsPng(Stream stream) {
// assuming stream is at position 0
return
stream.ReadByte() == 137 &&
stream.ReadByte() == 80 &&
stream.ReadByte() == 78 &&
stream.ReadByte() == 71 &&
stream.ReadByte() == 13 &&
stream.ReadByte() == 10 &&
stream.ReadByte() == 26 &&
stream.ReadByte() == 10;
}
这是非平凡的没有第三方库。 * c#pdf有很多匹配图像* –
您可以通过检查前4个字节来检测解码流是否为PNG。在PNG中,它们将包含ASCII中的字符串“PNG”。 –