C# adjust image brightness via Aspose.Imaging

FredGrit發表於2024-08-08
Install-Package Aspose.Imaging
 using (Aspose.Imaging.Image aspImg = Aspose.Imaging.Image.Load(rawImgUrl))
 {
     Aspose.Imaging.RasterImage rasterImg =  aspImg as Aspose.Imaging.RasterImage;
     if (rasterImg != null)
     {
         // Set the brightness value. The accepted values of brightness are in the range [-255, 255].
         rasterImg.AdjustBrightness(50);
         rasterImg.Save(adjustedFile);
     } 
 }

//Whole code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp44
{
    class Program
    {
        static void Main(string[] args)
        {
            AdjustImages();
            Console.ReadLine();
        }

        private static void AdjustImages()
        {
            var imgsList = Directory.GetFiles(@"../../Images");
            if(imgsList!=null && imgsList.Any())
            {
                int len = imgsList.Length;
                for(int i=0;i<len;i++)
                {
                    string adjustedImg = AdjustedImgBrightness(imgsList[i]);
                    Console.WriteLine($"Raw:{imgsList[i]},Adjusted:{adjustedImg}");
                }
            }
        }

        private static string AdjustedImgBrightness(string rawImgUrl)
        {
            if (!System.IO.File.Exists(rawImgUrl))
            {
                return string.Empty;
            }

            string fileName=System.IO.Path.GetFileNameWithoutExtension(rawImgUrl);
            string dir=System.IO.Path.GetDirectoryName(rawImgUrl);
            string adjustedFile = System.IO.Path.Combine(dir, fileName + "_adjusted.jpg");
            using (Aspose.Imaging.Image aspImg = Aspose.Imaging.Image.Load(rawImgUrl))
            {
                Aspose.Imaging.RasterImage rasterImg =  aspImg as Aspose.Imaging.RasterImage;
                if (rasterImg != null)
                {
                    // Set the brightness value. The accepted values of brightness are in the range [-255, 255].
                    rasterImg.AdjustBrightness(50);
                    rasterImg.Save(adjustedFile);
                } 
            }
            return adjustedFile;
        }
    }
}

相關文章