■■■

2016年4月3日日曜日

画像の彩度を変更する方法

画像の彩度を変更する方法
VB.NET
Public Shared Function ChangeSaturation(ByVal img As Image, _
ByVal saturation As Single) As Image

Dim newImg As New Bitmap(img.Width, img.Height)

Dim g As Graphics = Graphics.FromImage(newImg)

Dim cm As New System.Drawing.Imaging.ColorMatrix()
Const rwgt As Single = 0.3086F
Const gwgt As Single = 0.6094F
Const bwgt As Single = 0.082F
cm.Matrix01 = (1.0F - saturation) * rwgt
cm.Matrix02 = cm.Matrix01
cm.Matrix00 = cm.Matrix01 + saturation
cm.Matrix10 = (1.0F - saturation) * gwgt
cm.Matrix12 = cm.Matrix10
cm.Matrix11 = cm.Matrix10 + saturation
cm.Matrix20 = (1.0F - saturation) * bwgt
cm.Matrix21 = cm.Matrix20
cm.Matrix22 = cm.Matrix20 + saturation
cm.Matrix33 = 1
cm.Matrix44 = 1

Dim ia As New System.Drawing.Imaging.ImageAttributes()

ia.SetColorMatrix(cm)

g.DrawImage(img, New Rectangle(0, 0, img.Width, img.Height), _
0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia)

g.Dispose()

Return newImg
End Function
C#
public static Image ChangeSaturation(Image img, float saturation)
{

Bitmap newImg = new Bitmap(img.Width, img.Height);

Graphics g = Graphics.FromImage(newImg);

System.Drawing.Imaging.ColorMatrix cm =
new System.Drawing.Imaging.ColorMatrix();
const float rwgt = 0.3086f;
const float gwgt = 0.6094f;
const float bwgt = 0.0820f;
cm.Matrix01 = cm.Matrix02 = (1f - saturation) * rwgt;
cm.Matrix00 = cm.Matrix01 + saturation;
cm.Matrix10 = cm.Matrix12 = (1f - saturation) * gwgt;
cm.Matrix11 = cm.Matrix10 + saturation;
cm.Matrix20 = cm.Matrix21 = (1f - saturation) * bwgt;
cm.Matrix22 = cm.Matrix20 + saturation;
cm.Matrix33 = cm.Matrix44 = 1;

System.Drawing.Imaging.ImageAttributes ia =
new System.Drawing.Imaging.ImageAttributes();

ia.SetColorMatrix(cm);

g.DrawImage(img,
new Rectangle(0, 0, img.Width, img.Height),
0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia);

g.Dispose();

return newImg;
}

■■■