Skip to main content
 首页 » 编程设计

c#之BitmapImage 或 ImageStream 到图像文件之Windows 10

2024年05月29日41soundcode

我有Windows.Graphics.Imaging ImageStream .很容易将其作为 XAML 图像的来源:

BitmapImage bitmapImage = new BitmapImage(); 
bitmapImage.SetSource(imageStream); 
 
XAMLImage.Source = bitmapImage; 

但我不知道如何在 Windows 10 应用程序中将其保存为图像文件(png、jpg、...)。

谢谢帮助。

请您参考如下方法:

您不能将 BitmapImage 保存为 png 或 jpeg 文件,您应该使用 WriteableBitmap 来代替。

代码(如何将 WriteableBitmap 保存为 JPEG):

    var image = new WriteableBitmap(50, 50); 
 
    var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/StoreLogo.png")); 
 
    var content = await file.OpenReadAsync(); 
 
    image.SetSource(content); 
 
    var saveAsTarget = await KnownFolders.PicturesLibrary.CreateFileAsync("saveas.jpg"); 
 
    BitmapEncoder encoder = await BitmapEncoder.CreateAsync( 
        BitmapEncoder.JpegEncoderId,  
        await saveAsTarget.OpenAsync(FileAccessMode.ReadWrite)); 
 
    Stream pixelStream = image.PixelBuffer.AsStream(); 
 
    byte[] pixels = new byte[pixelStream.Length]; 
 
    await pixelStream.ReadAsync(pixels, 0, pixels.Length); 
 
    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96.0, 96.0, pixels); 
 
    await encoder.FlushAsync();