WPF(C#)中Bitmap与BitmapImage相互转换
程序员文章站
2023-11-18 18:57:40
一、WPF的Image控件中设置ImageSource 还可以使用: 还可以使用: 二、Bitmap转BitmapImage 先将Bitmap储存成memorystream,然后指定给BitmapImage 三、Bitmap转BitmapSource 四、BitmapSource转Bitmap ......
一、wpf的image控件中设置imagesource
image1.source = new bitmapimage(new uri(@"image file path", urikind.relativeorabsolute));
还可以使用:
system.io.filestream fs = new system.io.filestream(filepath, system.io.filemode.open, system.io.fileaccess.read); byte[] buffer = new byte[fs.length]; fs.read(buffer, 0, buffer.length); fs.close(); fs.dispose(); system.io.memorystream ms = new system.io.memorystream(buffer); bitmapimage bitmapimage = new bitmapimage(); bitmapimage.begininit(); bitmapimage.streamsource = ms; bitmapimage.cacheoption = bitmapcacheoption.onload; bitmapimage.endinit(); ms.dispose(); image1.source = bitmapimage;
还可以使用:
bitmapimage bitmapimage = new bitmapimage(); bitmapimage.begininit(); bitmapimage.cacheoption = bitmapcacheoption.onload; bitmapimage.urisource = new uri(szpath);//szpath为图片的全路径 bitmapimage.endinit(); bitmapimage.freeze(); image1.source = bitmapimage;
二、bitmap转bitmapimage
先将bitmap储存成memorystream,然后指定给bitmapimage
private bitmapimage bitmaptobitmapimage(system.drawing.bitmap bitmap) { bitmapimage bitmapimage = new bitmapimage(); using (system.io.memorystream ms = new system.io.memorystream()) { bitmap.save(ms, bitmap.rawformat); bitmapimage.begininit(); bitmapimage.streamsource = ms; bitmapimage.cacheoption = bitmapcacheoption.onload; bitmapimage.endinit(); bitmapimage.freeze(); } return bitmapimage; } image1.source = bitmaptobitmapimage(bitmap);
三、bitmap转bitmapsource
/*------------------------------------------------------------------------- //imaging.createbitmapsourcefromhbitmap方法,基于所提供的非托管位图和调色板信息的指针, //返回一个托管的bitmapsource ---------------------------------------------------------------------------*/ bitmap bitmap = capturescreen.getdesktopimage(); intptr ip = bitmap.gethbitmap();//从gdi+ bitmap创建gdi位图对象 bitmapsource bitmapsource = system.windows.interop.imaging.createbitmapsourcefromhbitmap(ip, intptr.zero, int32rect.empty, system.windows.media.imaging.bitmapsizeoptions.fromemptyoptions()); image1.source = bitmapsource;
四、bitmapsource转bitmap
bitmapsource m = (bitmapsource)image1.source; system.drawing.bitmap bmp = new system.drawing.bitmap(m.pixelwidth, m.pixelheight, system.drawing.imaging.pixelformat.format32bpppargb); system.drawing.imaging.bitmapdata data = bmp.lockbits( new system.drawing.rectangle(system.drawing.point.empty, bmp.size), system.drawing.imaging.imagelockmode.writeonly, system.drawing.imaging.pixelformat.format32bpppargb); m.copypixels(int32rect.empty, data.scan0, data.height * data.stride, data.stride); bmp.unlockbits(data);
上一篇: C#用抽象类定义几何图形