2010-08-26 32 views

Trả lời

10

Sử dụng phương pháp Create.

Ví dụ bị đánh cắp từ MSDN: :)

int width = 128; 
int height = width; 
int stride = width/8; 
byte[] pixels = new byte[height*stride]; 

// Try creating a new image with a custom palette. 
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>(); 
colors.Add(System.Windows.Media.Colors.Red); 
colors.Add(System.Windows.Media.Colors.Blue); 
colors.Add(System.Windows.Media.Colors.Green); 
BitmapPalette myPalette = new BitmapPalette(colors); 

// Creates a new empty image with the pre-defined palette 
BitmapSource image = BitmapSource.Create(
             width, height, 
             96, 96, 
             PixelFormats.Indexed1, 
             myPalette, 
             pixels, 
             stride); 
13

Nhờ Arcutus hint Tôi có này ngay bây giờ (mà hoạt động tốt):

var i = BitmapImage.Create(
    2, 
    2, 
    96, 
    96, 
    PixelFormats.Indexed1, 
    new BitmapPalette(new List<Color> { Colors.Transparent }), 
    new byte[] { 0, 0, 0, 0 }, 
    1); 

Nếu tôi làm cho hình ảnh này nhỏ hơn tôi nhận được một ArgumentException. Tôi không biết tại sao tôi không thể tạo ra một hình ảnh nhỏ hơn 2x2px.

+2

Bạn có thể bằng cách sử dụng định dạng khác (định dạng được lập chỉ mục đặc biệt hơn, nhưng tôi cũng không biết nguyên nhân chính xác). Ví dụ: BitmapSource.Create (1, 1, 96, 96, PixelFormats.Bgra32, null, byte mới [] {0, 0, 0, 0}, 4) (trong ví dụ này, bước tiến là bốn vì có bốn byte cho mỗi pixel trong Bgra32 và bốn byte trong mảng mô tả một pixel). chỉnh sửa: Trên thực tế, tôi cho rằng ví dụ của bạn cũng nên hoạt động, nếu bạn rút ngắn mảng byte thành một phần tử cho một pixel. –

+0

sử dụng các thông số của bạn (1, 1, 96, 96, PixelFormats.Bgra32, null, byte mới [] {0, 0, 0, 0}, 4) sẽ ngăn toàn bộ giao diện người dùng WPF hiển thị. – bitbonk

0

Chỉ cần xem xét điều này. Nó hoạt động cho bất kỳ Pixelformat

public static BitmapSource CreateEmtpyBitmapSource(int width, int height, PixelFormat pixelFormat) 
    { 
     PixelFormat pf = pixelFormat; 
     int rawStride = (width * pf.BitsPerPixel + 7)/8; 
     var rawImage = new byte[rawStride * height]; 
     var bitmap = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride); 
     return bitmap; 
    } 
3

Cách tạo hình ảnh như vậy mà không phân bổ mảng byte được quản lý lớn là sử dụng TransformedBitmap.

var bmptmp = BitmapSource.Create(1,1,96,96,PixelFormats.Bgr24,null,new byte[3]{0,0,0},3); 

var imgcreated = new TransformedBitmap(bmptmp, new ScaleTransform(width, height)); 
Các vấn đề liên quan