简体   繁体   中英

Save an Image with a new file name [ImageSharp]

I have upgraded my project from .net framework to .net 6 (core). In my project, there are many places where Bitmap is used. I have read in the microsoft documentations that System.Drawing.Common will only support the Windows platform and even after adding the EnableUnixSupport configuration, it will not be supported in net7.So, now I am using ImageSharp.Web. I have the scenario where I save a file as Image (the format is .tiff) then I read from that path as bitmap and save as PNG ( due to some business rule) Following is the line of code I am trying change:

Bitmap.FromFile(completePath).Save(pngPath, ImageFormat.Png);

This is the code I have converted into. The only issue is how to save as a new file name as the Tiff file has tiff in the file name.

string extension = _GetExtension(img.ContentType);
       


 if (extension == Constants.TiffExtension)
            {
           
            fileName = fileName.Replace(Constants.TiffExtension, "PNG");
           
            using (var outputStream = new FileStream(completePath, FileMode.CreateNew))
            {
                var image = SixLabors.ImageSharp.Image.Load(completePath);

                image.SaveAsync(outputStream, new PngEncoder()); //how to save new file name?
            }
           
        }

You can use the image.Save(fileName); overload to save a image to a file. The file name overload that takes just a path will automatically choose the correct encoder based on the file extension.

I was using the ImageSharp.Web package while the one I needed was the basic ImageSharp package. Special thanks to @James South for correcting me and @tocsoft for the guidance.

I have fixed it by the following code which is working:

 if (extension == Constants.Conversion.TiffExtension)
            {
                using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image.Load(completePath))
                {
                    string pngPath = completePath.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
                    image.Save(pngPath);
                    fileName = fileName.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
                }
            } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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