关于WriteableBitmap(wp7中) (转)
1. WriteableBitmap.SetSource 和 WriteableBitmap.LoadJpeg是不同的。
- constint CANVAS_WIDTH = 480;
- BitmapImage bmp = new BitmapImage();
- bmp.SetSource(stream); //stream为原始图片数据,例如可以是从文件中读到的
- int w = CANVAS_WIDTH;
- int h = CANVAS_WIDTH * bmp.PixelHeight / bmp.PixelWidth;
- WriteableBitmap wbmp = new WriteableBitmap(w, h);
- wbmp.SetSource(stream);
- WriteableBitmap wbmp2 = new WriteableBitmap(w, h);
- wbmp2.LoadJpeg(stream);
const int CANVAS_WIDTH = 480; BitmapImage bmp = new BitmapImage(); bmp.SetSource(stream); //stream为原始图片数据,例如可以是从文件中读到的 int w = CANVAS_WIDTH; int h = CANVAS_WIDTH * bmp.PixelHeight / bmp.PixelWidth; WriteableBitmap wbmp = new WriteableBitmap(w, h); wbmp.SetSource(stream); WriteableBitmap wbmp2 = new WriteableBitmap(w, h); wbmp2.LoadJpeg(stream);
执行完上述代码,wbmp的宽高为图片原始宽高,而wbmp2的宽高为修改过的宽高,即宽度限定为480像素了。简单来说,如果希望图片按指定的宽高载入,用LoadJpeg;希望保持原始宽高,用SetSource
2.
WriteableBitmap.Render(UIElement element, Transform transform) 可以将一个控件截图到WriteableBitmap中,但是注意,在这个函数之后调用WriteableBitmap.Invalidate() 才能正式生效。
构造函数WriteableBitmap(UIElement element, Transform transform)和Render作用类,但Render更灵活,可以在现有图上面继续叠加控件的截图
示例,生成一个1000*5000的白色位图
- WriteableBitmap wbmp = new WriteableBitmap(1000, 5000);
- long tick1 = DateTime.Now.Ticks;
- WriteableBitmap wbmp2 = new WriteableBitmap(1, 1);
- wbmp2.Pixels[0] = -1;
- Image img2 = new Image()
- {
- Source = wbmp2,
- Width = 1,
- Height = 1,
- Stretch = Stretch.None,
- HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
- VerticalAlignment = System.Windows.VerticalAlignment.Top
- };
- ScaleTransform trans2 = new ScaleTransform() { CenterX = 0, CenterY = 0, ScaleX = 1000, ScaleY = 5000 };
- wbmp.Render(img2, trans2);
- wbmp.Invalidate();
WriteableBitmap wbmp = new WriteableBitmap(1000, 5000); long tick1 = DateTime.Now.Ticks; WriteableBitmap wbmp2 = new WriteableBitmap(1, 1); wbmp2.Pixels[0] = -1; Image img2 = new Image() { Source = wbmp2, Width = 1, Height = 1, Stretch = Stretch.None, HorizontalAlignment = System.Windows.HorizontalAlignment.Left, VerticalAlignment = System.Windows.VerticalAlignment.Top }; ScaleTransform trans2 = new ScaleTransform() { CenterX = 0, CenterY = 0, ScaleX = 1000, ScaleY = 5000 }; wbmp.Render(img2, trans2); wbmp.Invalidate();
3. 内存
WriteableBitmap需要占=内存 宽*高*4
需要注意的是:在调用函数void SaveJpeg(this WriteableBitmap bitmap, Stream targetStream, int targetWidth, int targetHeight, int orientation, int quality)时,有一个瞬时需要额外占用内存 targetWidth*targetHeight*4.
如果图片很大而且内存已经很紧张了,这个时候可能导致内存溢出崩溃
注:这里将图片保存在MemeoryStream里和IsolatedStorageFileStream里差别不大。因为保存图片本身需要的控件不大(jpg格式,压缩过),消耗内存发生在中间过程,相当于位图展开了