c# - 在 WPF 中调整图像大小

标签 c# wpf image image-resizing

我有一张图片,我想调整它的大小并需要保存在我的临时文件夹中。

我试过的如下:

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;
}

但是当我像这样创建图像时,它会将部分图像保存在临时文件夹中。 (如上图所示)

enter image description here

如何重新调整完整图像的大小?我在这里错过了什么?

编辑: 正如 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;
}

最佳答案

至于调整大小本身,使用 WPF 的 TransformedBitmap 似乎更容易一些:

var bitmap = new TransformedBitmap(bitmapSource, 
    new ScaleTransform(
        newWidth / bitmapSource.PixelWidth, 
        newHeight / bitmapSource.PixelHeight));

关于c# - 在 WPF 中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15779564/

相关文章:

html - 在响应式环境中叠加两个图像

c# - 三元运算符语法来选择接口(interface)的实现

c# - UnityEngine.GameObject 与 Generic.List<UnityEngine.GameObject>

c# - 类似于 Mathf.Clamp 函数的东西?

c# - 确定在执行 ContextMenu MenuItem 时在 ListView 中单击了哪个 ListViewItem

c# - 在 WPF 中绘制动态多边形

c# - 在 TopShelf 中使用异步 WhenStarted 和 WhenStopped 方法

c# - 使用 MVVM 在 WPF 中创建新窗口的最佳方法

javascript - 如何检测图像对象是否正在显示?

javascript - 使用 jQuery 动态插入图像