WPF BitmapSource /BitmapImage 获取像素点颜色
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.ComponentModel;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows;
namespace WpfMosaic
{
[StructLayout(LayoutKind.Sequential)]
public struct PixelColor
{
public byte Blue;
public byte Green;
public byte Red;
public byte Alpha;
}
public class Utils
{
public static PixelColor[,] GetPixels(BitmapSource source)
{
if (source.Format != PixelFormats.Bgra32)
source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
PixelColor[,] pixels = new PixelColor[source.PixelWidth, source.PixelHeight];
int stride = source.PixelWidth * ((source.Format.BitsPerPixel + 7) / 8);
GCHandle pinnedPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
source.CopyPixels(
new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
pinnedPixels.AddrOfPinnedObject(),
pixels.GetLength(0) * pixels.GetLength(1) * 4,
stride);
pinnedPixels.Free();
return pixels;
}
}
}
设置颜色后保存图片:
public static Bitmap setColor(PixelColor[,] pixel) { Bitmap bmp = new Bitmap(1080,1920); // the target colors // var palette = new BitmapPalette(new List{ Colors.Yellow, Colors.Red }); int k = 0; for (int i = 0;i< 1080; i++) { for (int j = 0; j < bmp.Height; j++) { bmp.SetPixel(i, j, System.Drawing.Color.FromArgb(pixel[i,j].Alpha, pixel[i, j].Red, pixel[i, j].Green, pixel[i, j].Blue)); k++; } } bmp.Save(@"C:\Users\gwang\Pictures\0011122.jpg", ImageFormat.Jpeg); return bmp; }
// 用法:
//var pixels = GetPixels(image);
//if(pixels[7, 3].Red > 4)
上面发现颜色不对。。。。。。。。。。。。。
下面的发现 颜色变黄了:
public static PixelColor[,] GetPixels2(BitmapSource source)
{
PixelColor[,] result= new PixelColor[source.PixelWidth, source.PixelHeight];
int stride = source.PixelWidth * 4;
int size = source.PixelHeight * stride;
byte[] pixels = new byte[size];
source.CopyPixels(pixels, stride, 0);
for (int y = 0; y < source.PixelHeight; y++)
{
for (int x = 0; x < source.PixelWidth; x++)
{
int index = y * stride + 4 * x;
byte red = pixels[index];
byte green = pixels[index + 1];
byte blue = pixels[index + 2];
byte alpha = pixels[index + 3];
result[x, y] = new PixelColor()
{
Alpha = alpha,
Red = red,
Green = green,
Blue = blue
};
}
}
return result;
}
蛋疼。。。。。。。。。。。。。。。。。。。。