【发布时间】:2016-05-26 17:23:12
【问题描述】:
我正在使用 Windows。UI 是 C# 中的 Winform。 我在 Photoshop 中有文件图像;它是透明的。像这样:
所以,我想要这张图片的背景;它会显示。 例如,我选择橙色。
我试过了:
gbmp.Clear(Color.Orange);
但它会覆盖我的图片;图片只有一种颜色是橙色。
我的代码:
Graphics gra = Graphics.FromImage(img);
Bitmap bmp = new Bitmap(@"" + pathToFile);
panel2.BackgroundImage = bmp;
Graphics gbmp = Graphics.FromImage(bmp);
gbmp.Clear(Color.Orange);
gbmp.DrawImage(
DrawText("WHAT UP?", fontType, myColorLabel1,
Color.Transparent),
Point.Round(StretchImageSize(new Point(activeLabels[1].Location.X, activeLabels[1].Location.Y), panel2)));
gra.Dispose();
Guid id = Guid.NewGuid();
ScaleImage(bmp, witdhImg, heightImg)
.Save(linkLocation + "\\" + id + "." + imgType,
ImageFormat.Png);
我发现这篇文章就像How to Change Pixel Color of an Image in C#.NET
这是我使用 Pixels 完成的解决方案。
附上源代码,方便大家试一试,得到结果。
我有 128x128(宽 x 高)的示例图片。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
//using System.Globalization;
namespace colorchange
{
class Program
{
static void Main(string[] args)
{
try
{
Bitmap bmp = null;
//The Source Directory in debug\bin\Big\
string[] files = Directory.GetFiles("Big\\");
foreach (string filename in files)
{
bmp = (Bitmap)Image.FromFile(filename);
bmp = ChangeColor(bmp);
string[] spliter = filename.Split('\\');
//Destination Directory debug\bin\BigGreen\
bmp.Save("BigGreen\\" + spliter[1]);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static Bitmap ChangeColor(Bitmap scrBitmap)
{
//You can change your new color here. Red,Green,LawnGreen any..
Color newColor = Color.Red;
Color actualColor;
//make an empty bitmap the same size as scrBitmap
Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
for (int i = 0; i < scrBitmap.Width; i++)
{
for (int j = 0; j < scrBitmap.Height; j++)
{
//get the pixel from the scrBitmap image
actualColor = scrBitmap.GetPixel(i, j);
// > 150 because.. Images edges can be of low pixel colr. if we set all pixel color to new then there will be no smoothness left.
if (actualColor.A > 150)
newBitmap.SetPixel(i, j, newColor);
else
newBitmap.SetPixel(i, j, actualColor);
}
}
return newBitmap;
}
}
}
//下面是示例图像和应用不同颜色的不同结果
我们将非常感谢您修改代码。
它改变图像中的对象;它不能改变背景。
你有什么想法改变这段代码吗?
【问题讨论】:
-
您可以在图像上使用
SetPixel和GetPixel。如果GetPixel与颜色匹配,则使用SetPixel使其透明 -
@Bauss 我更新了我的问题。你能再看看这个问题吗?