Converting .HEIC to JPEG using imagick in C#

放肆的年华 提交于 2020-06-17 00:07:39

问题


I'm having trouble in converting heic file to jpeg

I have already tried searching it online, i can find how to write to a folder but not how to get a byte[] of a converted file so that i can save it

       byte[] file = null;
        file = Convert.FromBase64String(dto.File);

        //Convert HEIC/HEIF to JPF
        if (extension == "HEIC" || extension == "HEIF")
        {
          try
          {
           using (MagickImageCollection images = new MagickImageCollection())
            {
              images.Read(file);
              using (IMagickImage vertical = images.AppendVertically())
              {
                var imgname = filename + ".jpeg";
                vertical.Format = MagickFormat.Jpeg;
                vertical.Density = new Density(300);
                vertical.Write(imgname);
                extension = "jpeg";
            }
            }
          }
          catch (Exception ex)
          {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
          }
        }
            documentId = Service.AddSupportingDocument(file, extension , userName);

I'm not able to get the output file, it's just a string


回答1:


According to the documentation, and just like @SLaks suggested, you need to do it via a MemoryStream. Check this example straight from the docs:

// Read first frame of gif image
using (MagickImage image = new MagickImage("Snakeware.gif"))
{
    // Save frame as jpg
    image.Write("Snakeware.jpg");
}

// Write to stream
MagickReadSettings settings = new MagickReadSettings();
// Tells the xc: reader the image to create should be 800x600
settings.Width = 800;
settings.Height = 600;

using (MemoryStream memStream = new MemoryStream())
{
    // Create image that is completely purple and 800x600
    using (MagickImage image = new MagickImage("xc:purple", settings))
    {
        // Sets the output format to png
        image.Format = MagickFormat.Png;
        // Write the image to the memorystream
        image.Write(memStream);
    }
}

// Read image from file
using (MagickImage image = new MagickImage("Snakeware.png"))
{
    // Sets the output format to jpeg
    image.Format = MagickFormat.Jpeg;
    // Create byte array that contains a jpeg file
    byte[] data = image.ToByteArray();
}



回答2:


You need to create a MemoryStream, call .Write() to write the image to the memory stream, then call .ToArray() on the stream to get the bytes it wrote.



来源:https://stackoverflow.com/questions/56939187/converting-heic-to-jpeg-using-imagick-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!