1

I have a .NET c# web application that allows users to upload images. I installed the Magick.NET NuGet package. I'm attempting to convert uploaded .heic files to .jpg but I'm not sure where to start.

Here's the upload without Magick.net.

string fullPath = path + @"\Images\" + fileName;
Image image = Image.FromStream(postedFile.InputStream);

image.Save(path);

Here's what I'm trying but I get the following error: Parameter is not valid

string fullPath = path + @"\Images\" + fileName;
Bitmap bitmap = new Bitmap(postedFile.InputStream); <-- ERROR

using (MagickImage i = new MagickImage(bitmap))
{
    i.Format = MagickFormat.Jpg;

    using (MemoryStream memStream = new MemoryStream(i.ToByteArray()))
    {
        image = Image.FromStream(memStream);
    }
}

image.Save(path);

Here's another approach that's similar to the Magick.net documentation but I get the following error: Attempt by security transparent method to access security critical method failed. Assembly marked with the AllowPartiallyTrustedCallersAttribute and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

string fullPath = path + @"\Images\" + fileName;
Stream fs = postedFile.InputStream;
BinaryReader br = new System.IO.BinaryReader(fs);
byte[] bytes = br.ReadBytes((Int32)fs.Length);

using (MemoryStream memStream = new MemoryStream())
{
    using (MagickImage i = new MagickImage(bytes)) <-- ERROR
    {
        i.Format = MagickFormat.Jpg;

        image = Image.FromStream(memStream);
    }
}

image.Save(path);

Anyone have any suggestions?

user3321095
  • 185
  • 1
  • 10

1 Answers1

0

You don't need to instantiate a bitmap for that, and that error is probably because of your stream position (you need to set it to 0).

Here's what I did to make this work

postedFile.InputStream.Position = 0; //just to avoid the Parameter is not valid error in case you did any previous manipulation with this


using (MagickImage i = new MagickImage(postedFile.InputStream))
{
    i.Format = MagickFormat.Jpg;

    using (MemoryStream memStream = new MemoryStream(i.ToByteArray()))
    {
        image = Image.FromStream(memStream);
    }
}
Antonio Correia
  • 1,093
  • 1
  • 15
  • 22