去除黑色背景
Posted agchuanqi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了去除黑色背景相关的知识,希望对你有一定的参考价值。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Dictionary<string, string> dic = new Dictionary<string, string>();
private void Form1_Load(object sender, EventArgs e)
{
}
public Form1()
{
InitializeComponent();
ListFiles(new DirectoryInfo("f:/www5"));
}
public void modifyToPng(string sd, string sf)
{
Image srcImage = Image.FromFile(sf);
int resW = srcImage.Width;
int resH = srcImage.Height;
Bitmap resultImage = new Bitmap(resW, resH);
Graphics gg = Graphics.FromImage(resultImage);
gg.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
gg.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
gg.DrawImage(srcImage, new Rectangle(0, 0, resW, resH), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);
for (int i = 0; i < resW; i++)
{
for (int j = 0; j < resH; j++)
{
Color c = resultImage.GetPixel(i, j);
//透明度必须超过rgb最大差值
int dif1 = Math.Abs(c.R - c.G);
int dif2 = Math.Abs(c.R - c.B);
int dif3 = Math.Abs(c.G - c.B);
int maxDiff = Math.Max(dif1, Math.Max(dif2, dif3));
int a = (int)(0.2989 * c.R + 0.5866 * c.G + 0.1145 * c.B);
if (a > 255) a = 255;
if (a < maxDiff) a = maxDiff;
//保持颜色比例
int max = Math.Max(c.R, Math.Max(c.G, c.B));
if (max == 0) max = 1;
int rateR = 255 * c.R / max;
int rateG = 255 * c.G / max;
int rateB = 255 * c.B / max;
int r = c.R * 255 / (a == 0 ? 1 : a);
if (r > rateR) r = rateR;
int g = c.G * 255 / (a == 0 ? 1 : a);
if (g > rateG) g = rateG;
int b = c.B * 255 / (a == 0 ? 1 : a);
if (b > rateB) b = rateB;
resultImage.SetPixel(i, j, Color.FromArgb(a, r, g, b));
}
}
resultImage.Save(sf.Substring(0, sf.LastIndexOf(".")) + ".png", System.Drawing.Imaging.ImageFormat.Png);
}
public void ListFiles(FileSystemInfo info)
{
if (!info.Exists) return;
DirectoryInfo dir = info as DirectoryInfo;
//不是目录
if (dir == null) return;
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
{
//Console.WriteLine(file.FullName + " " + file.Length);
if (file.FullName.Substring(file.FullName.LastIndexOf(".")) == ".bmp")
//此处为显示JPG格式,不加IF可遍历所有格式的文件
{
//this.list1.Items.Add(file);
//MessageBox.Show(file.FullName.Substring(file.FullName.LastIndexOf(".")));
modifyToPng(file.DirectoryName, file.FullName);
}
}
//对于子目录,进行递归调用
else
{
ListFiles(files[i]);
}
}
}
}
}
以上是关于去除黑色背景的主要内容,如果未能解决你的问题,请参考以下文章