首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 影像放大畫質優化:InterpolationMode 與 PixelOffsetMode 設定

     編輯:關於C#

問題現象

使用 Graphics.DrawImage 放大圖片時,預設雙線性插值會導致邊緣模糊;需求為像素風格放大 (最近鄰插值),且發現左上角少半像素偏移。

解決方案

Graphics g = Graphics.FromImage(targetBitmap);

// 1. 最近鄰插值:保留銳利像素邊緣
g.InterpolationMode = InterpolationMode.NearestNeighbor;

// 2. 半像素偏移修正:解決左上角少半像素問題
g.PixelOffsetMode = PixelOffsetMode.Half;

原理說明

  • InterpolationMode.NearestNeighbor:對應 Java Swing 預設行為,不進行色彩插值,直接複製最近像素,適合像素藝術、QR Code、遊戲素材放大。
  • PixelOffsetMode.Half:GDI+ 預設以像素中心為座標原點,放大時產生 0.5 像素偏移;設為 Half 將渲染原點對齊像素邊界,消除邊界殘缺。

完整範例

public static Bitmap ScaleNearestNeighbor(Bitmap src, int scale)
{
    Bitmap dst = new Bitmap(src.Width * scale, src.Height * scale);
    using (Graphics g = Graphics.FromImage(dst))
    {
        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        g.PixelOffsetMode = PixelOffsetMode.Half;
        g.DrawImage(src, 0, 0, dst.Width, dst.Height);
    }
    return dst;
}

其他插值模式對照

小結

兩行屬性設定即可解決 C# 影像放大的畫質與對齊問題,記得在 DrawImage 前套用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
模式品質速度適用場景
NearestNeighbor低 (銳利)最快像素藝術、索引色
Bilinear中快一般照片縮放
Bicubic高較慢高品質照片放大
HighQualityBicubic最高最慢專業列印輸出