2016-11-15 33 views
0

我要求从亚马逊运输标签,他们发回一个字符串是一个压缩的“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(); 
    } 
+1

这是非平凡的没有第三方库。 * c#pdf有很多匹配图像* –

+0

您可以通过检查前4个字节来检测解码流是否为PNG。在PNG中,它们将包含ASCII中的字符串“PNG”。 –

回答

1

您可以通过查看前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"? 
} 

https://www.w3.org/TR/PNG/#5PNG-file-signature

+0

感谢您的回应! 但是,很难的是,即使我知道这是一个“PDF”我仍然无法将我的“PDF流”转换为PNG流,因此我可以将它打印为图像!任何解决方案 谢谢! – cmark

+0

啊,对不起,我误解了你的问题。我以为你只想显示PNG并需要一种方法来检测它们。不幸的是,我不知道如何将PDF转换为没有第三方库的图像。 –

+0

无论如何,这也是非常有用的! – cmark

0

...是改进@布拉德利的解决方案,以避免不必要的分配:

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; 
} 
+0

感谢您的回复!但是正如我告诉@布拉德利的困难之处在于,即使我知道这是一个“PDF或PNG”,我仍然无法将我的“PDF流”转换为PNG流,因此我可以将它打印为图像!任何解决方案谢谢! – cmark

+0

@cmark使用PDF渲染库。 https://www.google.com/search?q=pdf+rendering+library – Dai