C# 列印純黑白圖像要點

給自己備註的

如果使用的是條碼印表機列印圖像,由於條碼印表機沒有所謂顏色深淺的特性
其不是黑(Black)就是白(non-Black),如果要列印圖像(像是標籤上的LOGO),
圖片若是彩色的情況就會出現像是毛邊的點。

解決的方式就是要將圖片做灰階的二階化(threshold)

下面這個方法可以先產生一個二階化圖像的ImageAttributes:


        static ImageAttributes BWThreshold(Image sourceImage, float ThresholdLevel)
        {
            var gray_matrix = new float[][] {
                new float[] { 0.299f, 0.299f, 0.299f, 0, 0 },
                new float[] { 0.587f, 0.587f, 0.587f, 0, 0 },
                new float[] { 0.114f, 0.114f, 0.114f, 0, 0 },
                new float[] { 0,      0,      0,      1, 0 },
                new float[] { 0,      0,      0,      0, 1 }
            };
            var ia = new System.Drawing.Imaging.ImageAttributes();
            using (Graphics gr = Graphics.FromImage(sourceImage))
            {
                ia.SetColorMatrix(new System.Drawing.Imaging.ColorMatrix(gray_matrix));
                ia.SetThreshold(ThresholdLevel); // Change this threshold as needed
            }
            return ia;
        }


再把這個ImageAttributes丟給DrawImage當成參數輸入,即可繪製。

Image logopic = Image.FromFile(logoFile);
Rectangle logoRect = new Rectangle(10,10,230,120);
Graphics.DrawImage(
     logopic ,
     logoRect ,
     0 ,
     0 ,
     logopic.Width ,
     logopic.Height ,
     GraphicsUnit.Pixel ,
     BWThreshold(logopic,0.8f));

這樣可以把黑白圖像印製的比較清晰。

留言

Snowmeow寫道…
請問protected static ImageAttributes BWThreshold(Image sourceImage, float ThresholdLevel)
第二個參數ThresholdLevel要輸入多少?才是正確的?
WILDOX寫道…
Re: Snowmeow <7602782856541864734>

ThresholdLevel 這個數值只有 1 ←→ 0 ,0為全黑,1為全白
通常我們使用值為 0.3~0.7 之間,

但是,這不是絕對,必須視你的彩色圖片狀況,如果你的彩色圖片屬於平均顏色都很淡的情況 ThresholdLevel 就不可以調太高以免全部變白。

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式