我试图通过将PNG上的alpha值复制到另一个相同大小的图像上,从而使用alpha通道从PNG中创建剪贴蒙版。全部使用LockBits,然后使用UnlockBits。看来我的频道设置正确,但我没有看到它在后续的绘图操作中使用。
为了尽可能地简化事情,我使用了几乎相同的逻辑来仅在单个图像中设置红色通道值,但在保存图像之后,再次没有变化。如果我单步执行代码,则正确设置红色通道有效。这是简化的代码。任何意见或帮助表示赞赏。
var image = Image.FromFile(@"C:\imaging\image.jpg");
image.LoadRed();
image.Save(@"C:\imaging\output.jpg");
// image.jpg and output.jpg are the same.
// I would expect output to be washed over with lots of red but it isn't
public static void LoadRed(this Image destination)
{
var destinationBitmap = new Bitmap(destination);
const int blueChannel = 0;
const int greenChannel = 1;
const int redChannel = 2;
const int alphaChannel = 3;
var rec = new Rectangle(Point.Empty, destination.Size);
var destinationData = destinationBitmap.LockBits(rec, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
unsafe
{
byte* destinationPointer = (byte*)destinationData.Scan0.ToPointer();
destinationPointer += redChannel;
for (int i = rec.Width * rec.Height; i > 0; i--)
{
*destinationPointer = 255;
destinationPointer += 4;
}
}
destinationBitmap.UnlockBits(destinationData);
}
答案 0 :(得分:2)
您的问题与使用扩展方法的图像作为参数创建新的Bitmap实例有关。但是,一旦方法完成,您将保存原始图像,而不是保存修改后的位图。
更改扩展方法以处理System.Drawing.Bitmap的类型。