如何从BitmapImage获取数组System.Windows.Media.Color? [英] How to get an array System.Windows.Media.Color from a BitmapImage?

查看:146
本文介绍了如何从BitmapImage获取数组System.Windows.Media.Color?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个用于编辑图标的项目,我需要加载一个图标。我使用以下代码保存此图标:

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.

推荐答案

以下代码是我的问题的解决方案(使用位图):

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.

这篇关于如何从BitmapImage获取数组System.Windows.Media.Color?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆