C#修改圖片尺寸以及不改變原有圖片比例
更新時間:2025年01月07日 15:33:02 作者:syd二寶
文章介紹了如何使用C#中的Bitmap類來修改圖片尺寸,同時保持原有的圖片比例,作者分享了自己的經(jīng)驗,并鼓勵讀者參考和使用
C#修改圖片尺寸不改變原有圖片比例
C#使用BitMap修改圖片尺寸
修改圖片大小,不改變原有圖片比例

修改后圖片

代碼
public static void image()
{
System.Drawing.Image img = System.Drawing.Image.FromFile("圖片路徑");
Bitmap bt = new Bitmap(img);
//獲取圖片位置顏色
Color cl = bt.GetPixel(10, 10);
int Width = img.Width;
int Height = img.Height;
int marginx = Height / 2;
float dpiX = img.HorizontalResolution;
float dpiY = img.VerticalResolution;
//設(shè)置新圖的大小
Bitmap bitmap= new Bitmap(Width, Width, PixelFormat.Format24bppRgb);
//設(shè)置位圖文件的水平和垂直分辨率,與Img一致
bitmap.SetResolution(dpiX, dpiY);
//在位圖文件上填充一個新圖
Graphics graphics = Graphics.FromImage(bitmap);
System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Width, Width);
//定義顏色
SolidBrush mySolidBrush = new SolidBrush(cl);
//將新圖填充為獲取原圖位置的顏色
graphics.FillRectangle(mySolidBrush, Rec);
//向新圖中填充Img
graphics.DrawImage(img, 0, marginx, Rec, GraphicsUnit.Pixel);
graphics.Dispose();
GC.Collect();
bitmap.Save("保存圖片路徑", System.Drawing.Imaging.ImageFormat.Jpeg);
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#使用動態(tài)規(guī)劃解決0-1背包問題實例分析
這篇文章主要介紹了C#使用動態(tài)規(guī)劃解決0-1背包問題,實例分析了C#動態(tài)規(guī)劃算法的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04
使用HttpHanlder處理404:File not found的問題
本篇文章小編為大家介紹。使用HttpHanlder處理404:File not found的問題。需要的朋友參考下2013-04-04
WinForm實現(xiàn)仿視頻播放器左下角滾動新聞效果的方法
這篇文章主要介紹了WinForm實現(xiàn)仿視頻播放器左下角滾動新聞效果的方法,涉及WinForm窗口滾動字幕設(shè)置的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08

