How to Copy and Resize Image in Windows 10 UWP

前端 未结 1 630
长情又很酷
长情又很酷 2020-12-11 04:58

I have used the code from http://www.codeproject.com/Tips/552141/Csharp-Image-resize-convert-and-save to resize images programmatically. However, that project uses the

相关标签:
1条回答
  • 2020-12-11 05:49

    I may want to return a copy of the original BitmapImage rather than modifying the original.

    There is no good method to directly copy a BitmapImage, but we can reuse StorageFile for several times.

    If you just want to select a picture, show it and in the meanwhile show the re-sized picture of original one, you can pass the StorageFile as parameter like this:

    public static async Task<BitmapImage> ResizedImage(StorageFile ImageFile, int maxWidth, int maxHeight)
    {
        IRandomAccessStream inputstream = await ImageFile.OpenReadAsync();
        BitmapImage sourceImage = new BitmapImage();
        sourceImage.SetSource(inputstream);
        var origHeight = sourceImage.PixelHeight;
        var origWidth = sourceImage.PixelWidth;
        var ratioX = maxWidth / (float)origWidth;
        var ratioY = maxHeight / (float)origHeight;
        var ratio = Math.Min(ratioX, ratioY);
        var newHeight = (int)(origHeight * ratio);
        var newWidth = (int)(origWidth * ratio);
    
        sourceImage.DecodePixelWidth = newWidth;
        sourceImage.DecodePixelHeight = newHeight;
    
        return sourceImage;
    }
    

    In this scenario you just need to call this task and show the re-sized image like this:

    smallImage.Source = await ResizedImage(file, 250, 250);
    

    If you want to keep the BitmapImage parameter due to some reasons (like the sourceImage might be a modified bitmap but not directly loaded from file), and you want to re-size this new picture to another one, you will need to save the re-sized picture as a file at first, then open this file and re-size it again.

    0 讨论(0)
提交回复
热议问题