这是原始图像Colorslevels1.jpg:
然后,我使用这两种方法从图像中获取特定 colored颜色 ,并将这些 colored颜色 添加到新图像中.
private List<Color> GetColors()
{
if (bmp != null)
{
List<string> targetColors = new List<string>
{
"#ff00fe",
"#d00078",
"#e10a12",
"#fb3f00",
"#ff7d01",
"#ffa800",
"#ffcf00",
"#fefd19",
"#7cff21",
"#12f218",
"#01d31c",
"#00b02c",
"#008c4d",
"#00a09b",
"#00c3c9",
"#0165ef"
};
bmp = new Bitmap(@"d:\Ffmpeg Capture\colorslevels1.jpg");
int width = bmp.Width;
int height = bmp.Height;
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
Color c = bmp.GetPixel(i, j);
string hexColor = ColorTranslator.ToHtml(c).ToLower(); // Convert to lowercase
// Check if the lowercase hex color matches any of the target colors
if (targetColors.Contains(hexColor))
{
colors.Add(c);
}
}
}
bmp.Dispose();
// Save the bitmap with the colors once all colors are collected
SaveColorsAsBitmap(colors, @"d:\test.bmp");
}
return colors;
}
此方法将十六进制 colored颜色 保存为位图到硬盘.
private void SaveColorsAsBitmap(List<Color> colors, string filePath)
{
// Determine the dimensions of the bitmap
int width = 200; // Set the desired width (adjust as needed)
int height = colors.Count; // Set the height to the number of colors
// Create a new transparent bitmap with the determined dimensions
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bitmap))
{
// Clear the background to transparent
g.Clear(Color.Transparent);
// Draw each color as a vertical line on the bitmap
for (int i = 0; i < height; i++)
{
using (SolidBrush brush = new SolidBrush(colors[i]))
{
g.FillRectangle(brush, 0, i, width, 1);
}
}
}
// Save the bitmap as a PNG file (PNG supports transparency)
bitmap.Save(filePath, ImageFormat.Png);
// Dispose of the bitmap to release resources
bitmap.Dispose();
}
在方法SaveColorsAsBitmap中,我将宽度值设置为200,因为这样会太小,无法看到新位图图像中的 colored颜色 .在原始版本中,宽度值为1.
结果是:
在结果中,新图像具有我想要的 colored颜色 ,但每种 colored颜色 的宽度/高度和 colored颜色 数量与原始图像中的不同.这是我想要从原始图像中获得的顺序和 colored颜色 ,但每种 colored颜色 的大小(宽度/高度)与原始图像不同.
我如何修复它才能得到原始图像中的 colored颜色 ?