How to get an array System.Windows.Media.Color from a BitmapImage?

微笑、不失礼 提交于 2019-12-12 05:54:54

问题


I'm working on a project for edit icons and I need to load an icon. I use the following code for save this icon:

        var sd = new SaveFileDialog();
        sd.ShowDialog();
        sd.Filter = "File *.ico|*.ico";
        sd.FilterIndex = 0;
        var path = sd.FileName;
        if (!sd.CheckPathExists) return;

        var w = new WriteableBitmap(Dimention, Dimention, 1, 1, PixelFormats.Pbgra32, null);
        var pix = new int[Dimention,Dimention];
        for (int i = 0; i < Dimention; i++)
            for (int j = 0; j < Dimention; j++)
                pix[i, j] = ToArgb(IconCanvas.Board[i, j].Background.Color);

        w.WritePixels(new Int32Rect(0, 0, Dimention, Dimention), pix, Dimention*4, 0, 0);
        var e = new BmpBitmapEncoder();
        e.Frames.Add(BitmapFrame.Create(w));
        var file = new FileStream(path, FileMode.Create);
        e.Save(file);
        file.Close();

So, I need get an Color[,] from these images saved. I assume the icon's size is a square (width = height) . Thanks for your help.


回答1:


The following code is the solution for my problem (using a Bitmap):

// get the BitmapImage
var image = new BitmapImage(new Uri(path));
if (image.PixelHeight != image.PixelWidth) return;
Dimension = image.PixelHeight;

// copy to byte array
int stride = image.PixelWidth * 4;
byte[] buffer = new byte[stride * image.PixelHeight];
image.CopyPixels(buffer, stride, 0);

// create a bitmap
var bitmap = new System.Drawing.Bitmap(image.PixelWidth, image.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

// lock bitmap data
System.Drawing.Imaging.BitmapData bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat);

// copy byte array to bitmap data
System.Runtime.InteropServices.Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);

// unlock
bitmap.UnlockBits(bitmapData);

// copy to Color array
var colors = new Color[Dimension, Dimension];
for (int i = 0; i < bitmap.Height; i++)
    for (int j = 0; j < bitmap.Width; j++)
    {
        var mediacolor = bitmap.GetPixel(i, j);
        var drawingcolor = Color.FromArgb(mediacolor.A, mediacolor.R, mediacolor.G, mediacolor.B);
        colors[i, j] = drawingcolor;
    }

I hope that solved this problem if you need it.



来源:https://stackoverflow.com/questions/13748781/how-to-get-an-array-system-windows-media-color-from-a-bitmapimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!