简体   繁体   English

如何使用 iText7 从 C# 中的 MemoryStream 创建 Image 对象?

[英]How do you create an Image object from a MemoryStream in C# using iText7?

I am working with iText7 in ASP.NET-MVC v5.2.我正在 ASP.NET-MVC v5.2 中使用 iText7。 I am very inexperienced with iText and C# am still trying to figure out how the classes in this library work.我对 iText 非常缺乏经验,C# 仍在尝试弄清楚这个库中的类是如何工作的。

Say I have a MemoryStream which contains an image...假设我有一个包含图像的MemoryStream ......

MemoryStream imgStream = new MemoryStream(imgLocation);

How can I create an Image object using imgStream ?如何使用imgStream创建 Image 对象? I am looking for something along the lines of我正在寻找类似的东西

Image img = new Image(imgStream);

Thanks for the help :)谢谢您的帮助 :)

EDIT : I am trying to create an Image from iText not System.Drawing.Image编辑:我正在尝试从 iText 而非System.Drawing.Image创建图像

To create an iText 7 Image object from a bitmap image, you first have to create an ImageData instance which you then can feed into one of the corresponding Image constructors要从位图图像创建 iText 7 Image对象,您首先必须创建一个ImageData实例,然后您可以将其提供给相应的Image构造函数之一

public Image(ImageData img);
public Image(ImageData img, float left, float bottom);
public Image(ImageData img, float left, float bottom, float width);

You usually create an ImageData instance using the corresponding ImageDataFactory static methods:您通常使用相应的ImageDataFactory静态方法创建一个ImageData实例:

public static ImageData Create(byte[] bytes);
public static ImageData Create(String filename);
public static ImageData Create(Uri url);

As you see, there is no method for a stream.如您所见,流没有方法。 But as your stream is a MemoryStream , you can easily retrieve a byte[] of the image.但由于您的流是MemoryStream ,您可以轻松检索图像的byte[] Thus,因此,

byte[] imageBytes = imgStream.ToArray();
ImageData rawImage = ImageDataFactory.Create(imageBytes);
Image image = new Image(rawImage);

Convert the MemoryStream to a byte[] and use the GetInstance method将 MemoryStream 转换为byte[]并使用GetInstance方法

public static byte[] GetByteArray(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

and then use the byte array like this然后像这样使用字节数组

var Image = Image.GetInstance(GetByteArray(imgStream));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM