using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
public class BlackImageGenerator
{
public static ImageSource CreateBlackImage(int width, int height)
{
// 创建一个新的 WriteableBitmap 实例
var bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgr32, null);
// 获取位图的数据视图
var pixels = new byte[width * height * (PixelFormats.Bgr32.BitsPerPixel / 8)];
// 将所有像素设置为黑色
for (var i = 0; i < pixels.Length; i += 4)
{
// Bgr32 格式下,每四个字节表示一个像素,分别是 Blue, Green, Red, Alpha
pixels[i] = 0; // Blue
pixels[i + 1] = 0; // Green
pixels[i + 2] = 0; // Red
pixels[i + 3] = 255; // Alpha (fully opaque)
}
// 锁定位图以写入像素数据
bitmap.Lock();
// 将像素数据复制到位图中
bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * (PixelFormats.Bgr32.BitsPerPixel / 8), 0);
// 解锁位图
bitmap.Unlock();
return bitmap;
}
}
// 使用示例
var blackImageSource = BlackImageGenerator.CreateBlackImage(100, 100);
var image = new Image { Source = blackImageSource };
WPF生成一张全黑的图片
最新推荐文章于 2024-06-30 14:45:46 发布