Tutorial ini akan menunjukkan kepada Anda bagaimana Anda dapat mengubah ukuran gambar secara dinamis di ASP.Net C#.
Anda perlu mengimpor namaspace untuk situs Anda.
//required .net objects using System.Drawing; using System.Drawing.Imaging;
Fungsi berikut akan mengubah ukuran gambar dengan menerima dimensi gambar yang Anda butuhkan, diikuti dengan lokasi di mana gambar berada dan terakhir di mana Anda ingin menyimpan gambar yang diperbarui/diubah ukurannya.
//function to resize image public static void ResizeImage(int size, string filePath, string saveFilePath) { //variables for image dimension/scale double newHeight = 0; double newWidth = 0; double scale = 0; //create new image object Bitmap curImage = new Bitmap(filePath); //Determine image scaling if (curImage.Height > curImage.Width) { scale = Convert.ToSingle(size) / curImage.Height; } else { scale = Convert.ToSingle(size) / curImage.Width; } if (scale < 0 || scale > 1) { scale = 1;} //New image dimension newHeight = Math.Floor(Convert.ToSingle(curImage.Height) * scale); newWidth = Math.Floor(Convert.ToSingle(curImage.Width) * scale); //Create new object image Bitmap newImage = new Bitmap(curImage, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight)); Graphics imgDest = Graphics.FromImage(newImage); imgDest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; imgDest.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; imgDest.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; imgDest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders(); EncoderParameters param = new EncoderParameters(1); param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); //Draw the object image imgDest.DrawImage(curImage, 0, 0, newImage.Width, newImage.Height); //Save image file newImage.Save(saveFilePath, info[1], param); //Dispose the image objects curImage.Dispose(); newImage.Dispose(); imgDest.Dispose(); }
Demikian, Mudah2an Anda mungkin tertarik dengan artikel kami yang lain tentang Cara memotong gambar di ASP.Net C#
0 Komentar