2010-08-26 25 views

Respuesta

10

Utilice el método Create.

Ejemplo robado de 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

Gracias a Arcutus hint que tienen esta ahora (wich funciona bien):

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

Si hago esta imagen más pequeña consigo un ArgumentException. No tengo idea de por qué no puedo crear una imagen más pequeña que 2x2px.

+2

Puede hacerlo, usando un formato diferente (los formatos indexados son más peculiares, pero tampoco sé la razón exacta). Por ejemplo: BitmapSource.Create (1, 1, 96, 96, PixelFormats.Bgra32, null, nuevo byte [] {0, 0, 0, 0}, 4) (en este ejemplo, el paso grande es cuatro porque hay cuatro bytes por píxel en Bgra32, y los cuatro bytes en la matriz describen el píxel). editar: En realidad, creo que su ejemplo debería funcionar también, si acorta la matriz de bytes a un elemento para un píxel. –

+0

usando sus parámetros (1, 1, 96, 96, PixelFormats.Bgra32, nulo, nuevo byte [] {0, 0, 0, 0}, 4) evitará que toda la interfaz de usuario de WPF se renderice. – bitbonk

0

Eche un vistazo a esto. Funciona para cualquier 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

La manera de crear una imagen así sin asignar una gran matriz de bytes conseguido es utilizar 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));