我有一个图像,我想重新调整大小,需要保存在我的临时文件夹中。
我的尝试如下:
UIElement uie = CanvasHost.Child;
int width = 800;
int height = (int)((width / (double)((FrameworkElement)uie).Width) * (int)((FrameworkElement)uie).Height);
RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
rtb.Render(uie);
string dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\temp\";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
long size = 0;
string filePath = dir + DateTime.Now.Ticks.ToString() + (isPng ? ".png" : ".jpg");
BitmapEncoder enc = null;
using (FileStream fs = File.Create(filePath))
{
if (isPng)
enc = new PngBitmapEncoder();
else
enc = new JpegBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(rtb));
enc.Save(fs);
size = fs.Length;
}
但是当我像这样创建图像时,它会将部分图像保存在临时文件夹中。 (如上图所示)
我怎样才能调整完整图像的大小?我错过了什么?
编辑: 正如Erti-Chris Eelmaa所提到的上述答案所述,我已经更改了以下代码。它有效......
UIElement uie = CanvasHost.Child;
int width = DataCache.Instance.CurrentProject.MaxPhotoEdgeSize;
int height = (int)((width / (double)((FrameworkElement)uie).Width) * (int)((FrameworkElement)uie).Height);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)((FrameworkElement)uie).Width, (int)((FrameworkElement)uie).Height, 96, 96, PixelFormats.Pbgra32);
rtb.Render(uie);
ImageSource im = (ImageSource)rtb.Clone();
BitmapFrame bp = CreateResizedImage(im, width, height, 1); //method suggested by Erti-Chris Eelmaa
string dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\temp\";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
long size = 0;
string filePath = dir + DateTime.Now.Ticks.ToString() + (isPng ? ".png" : ".jpg");
BitmapEncoder enc = null;
using (FileStream fs = File.Create(filePath))
{
if (isPng)
enc = new PngBitmapEncoder();
else
enc = new JpegBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bp));
enc.Save(fs);
size = fs.Length;
}
答案 0 :(得分:19)
关于调整大小本身,使用WPF TransformedBitmap
似乎更容易:
var bitmap = new TransformedBitmap(bitmapSource,
new ScaleTransform(
newWidth / bitmapSource.PixelWidth,
newHeight / bitmapSource.PixelHeight));
答案 1 :(得分:16)
只需使用此方法获取BitmapFrame,之后您可以使用PngBitmapEncoder将其保存到HDD。
private static BitmapFrame CreateResizedImage(ImageSource source, int width, int height, int margin)
{
var rect = new Rect(margin, margin, width - margin * 2, height - margin * 2);
var group = new DrawingGroup();
RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality);
group.Children.Add(new ImageDrawing(source, rect));
var drawingVisual = new DrawingVisual();
using (var drawingContext = drawingVisual.RenderOpen())
drawingContext.DrawDrawing(group);
var resizedImage = new RenderTargetBitmap(
width, height, // Resized dimensions
96, 96, // Default DPI values
PixelFormats.Default); // Default pixel format
resizedImage.Render(drawingVisual);
return BitmapFrame.Create(resizedImage);
}