0

我需要根据某种颜色创建图像。颜色会有所不同,输出图像的大小也会有所不同。我想创建位图并将其保存到应用程序的临时文件夹中。我该怎么做呢?

我最初的要求来自颜色列表,并在 UI 中提供颜色示例。如果图像的大小是可变的,那么我可以为某些场景(例如搜索窗格中的结果建议)创建它们。

4

1 回答 1

0

这并不容易。但这一切都包含在这个单一的方法中供您使用。我希望它有所帮助。无论如何,这是基于给定颜色和大小创建位图的代码:

private async System.Threading.Tasks.Task<Windows.Storage.StorageFile> CreateThumb(Windows.UI.Color color, Windows.Foundation.Size size)
{
    // create colored bitmap
    var _Bitmap = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap((int)size.Width, (int)size.Height);
    byte[] _Pixels = new byte[4 * _Bitmap.PixelWidth * _Bitmap.PixelHeight];
    for (int i = 0; i < _Pixels.Length; i += 4)
    {
        _Pixels[i + 0] = color.B;
        _Pixels[i + 1] = color.G;
        _Pixels[i + 2] = color.R;
        _Pixels[i + 3] = color.A;
    }

    // update bitmap data
    // using System.Runtime.InteropServices.WindowsRuntime;
    using (var _Stream = _Bitmap.PixelBuffer.AsStream())
    {
        _Stream.Seek(0, SeekOrigin.Begin);
        _Stream.Write(_Pixels, 0, _Pixels.Length);
        _Bitmap.Invalidate();
    }

    // determine destination
    var _Folder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
    var _Name = color.ToString().TrimStart('#') + ".png";

    // use existing if already
    Windows.Storage.StorageFile _File;
    try { return await _Folder.GetFileAsync(_Name); }
    catch { /* do nothing; not found */ }
    _File = await _Folder.CreateFileAsync(_Name, Windows.Storage.CreationCollisionOption.ReplaceExisting);

    // extract stream to write
    // using System.Runtime.InteropServices.WindowsRuntime;
    using (var _Stream = _Bitmap.PixelBuffer.AsStream())
    {
        _Pixels = new byte[(uint)_Stream.Length];
        await _Stream.ReadAsync(_Pixels, 0, _Pixels.Length);
    }

    // write file
    using (var _WriteStream = await _File.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
    {
        var _Encoder = await Windows.Graphics.Imaging.BitmapEncoder
            .CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, _WriteStream);
        _Encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
            Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied,
            (uint)_Bitmap.PixelWidth, (uint)_Bitmap.PixelHeight, 96, 96, _Pixels);
        await _Encoder.FlushAsync();
        using (var outputStream = _WriteStream.GetOutputStreamAt(0))
            await outputStream.FlushAsync();
    }

    return _File;
}

祝你好运!

于 2013-05-15T20:42:09.580 回答