在Silverlight中缩放PNG图像

时间:2011-06-29 09:13:59

标签: silverlight-4.0 png image-scaling

在我的应用程序中,我接受用户的图像。如果图像大于指定大小,那么我将缩小到适当的大小并保存在数据库中。我正在使用FJCore库来缩放图像。该库适用于JPEG图像。但它不支持PNG图像。最近似乎没有更新库。任何想法如何在Silverlight中完成?

2 个答案:

答案 0 :(得分:0)

您可以做的是创建一个新的Image元素并将其源设置为从流创建的可写位图,但不要将此Image元素添加到可视树中。创建另一个所需最终大小的WriteableBitmap,然后在此WriteableBitmap上调用render,传递Image元素和ScaleTransform,以将图像大小调整为适当的大小。然后,您可以使用第二个WriteableBitmap作为第二个Image元素的源,并将其添加到可视树中。

答案 1 :(得分:0)

我使用WriteableBitmap项目来实现这一目标。如果有人需要,这是代码。

private void ShowCustomImageButton_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openDialog = new OpenFileDialog();
        openDialog.Multiselect = false;
        openDialog.Filter = "PNG Files|*.PNG";
        bool? userClickedOK = openDialog.ShowDialog();
        if (userClickedOK == true)
        {                
            BitmapImage image = new BitmapImage();
            // get image that user has selected.
            image.SetSource(openDialog.File.OpenRead());
            WriteableBitmap wrtbmp = new WriteableBitmap(image);
            // resize image if needed.
            wrtbmp = wrtbmp.Resize(64, 64, WriteableBitmapExtensions.Interpolation.NearestNeighbor);
            var img = wrtbmp.ToImage();
            // convert image into file stream.
            Stream filestram = img.ToStream();
            filestram.Position = 0;
            using (filestram)
            {
                // convert file stream into memory stream.
                var memoryStream = new MemoryStream();
                byte[] aryBuffer = new byte[16384];
                int nRead = filestram.Read(aryBuffer, 0, aryBuffer.Length);
                while (nRead > 0)
                {
                    memoryStream.Write(aryBuffer, 0, nRead);
                    nRead = filestram.Read(aryBuffer, 0, aryBuffer.Length);
                }
                // use following line to convert in bytes and save into database.
                memoryStream.ToArray();
                imgCustomImage.Source = CreateBitmapImage(memoryStream);
            }                        
        }
    }

    private BitmapImage CreateBitmapImage(MemoryStream memoryStream)
    {
        if ((memoryStream == null) || (memoryStream.Length == 0))
            return null;         

        var image = new BitmapImage();
        image.SetSource(memoryStream);
        return image;      
    }