XAML-Map-Control/MapControl/WPF/ImageLoader.WPF.cs

90 lines
2.8 KiB
C#
Raw Normal View History

// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2024-02-03 21:01:53 +01:00
// Copyright © 2024 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
2022-11-30 17:59:38 +01:00
using System;
using System.IO;
using System.Threading.Tasks;
2023-08-18 17:44:33 +02:00
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace MapControl
{
public static partial class ImageLoader
{
public static ImageSource LoadImage(Uri uri)
{
return new BitmapImage(uri);
}
2023-08-18 17:44:33 +02:00
public static ImageSource LoadImage(Stream stream)
{
2023-08-18 17:44:33 +02:00
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
image.Freeze();
return image;
}
2023-08-18 17:44:33 +02:00
public static Task<ImageSource> LoadImageAsync(Stream stream)
{
2023-08-18 17:44:33 +02:00
return Task.FromResult(LoadImage(stream));
}
2021-11-28 23:50:27 +01:00
public static Task<ImageSource> LoadImageAsync(string path)
{
2024-05-22 16:15:29 +02:00
if (!File.Exists(path))
{
2024-05-22 16:15:29 +02:00
return Task.FromResult<ImageSource>(null);
}
2024-05-22 16:15:29 +02:00
return Task.Run(() =>
{
2021-11-28 23:50:27 +01:00
using (var stream = File.OpenRead(path))
{
return LoadImage(stream);
}
});
}
2022-11-30 17:59:38 +01:00
internal static async Task<ImageSource> LoadMergedImageAsync(Uri uri1, Uri uri2, IProgress<double> progress)
{
2024-05-22 16:15:29 +02:00
var images = await LoadImagesAsync(uri1, uri2, progress);
2022-11-30 17:59:38 +01:00
2024-05-22 16:15:29 +02:00
WriteableBitmap image = null;
2022-11-30 17:59:38 +01:00
if (images.Length == 2 &&
images[0] is BitmapSource image1 &&
images[1] is BitmapSource image2 &&
image1.PixelHeight == image2.PixelHeight &&
image1.Format == image2.Format &&
image1.Format.BitsPerPixel % 8 == 0)
{
var format = image1.Format;
var height = image1.PixelHeight;
2023-08-18 17:44:33 +02:00
var width1 = image1.PixelWidth;
var width2 = image2.PixelWidth;
var stride1 = width1 * format.BitsPerPixel / 8;
var stride2 = width2 * format.BitsPerPixel / 8;
2022-11-30 17:59:38 +01:00
var buffer1 = new byte[stride1 * height];
var buffer2 = new byte[stride2 * height];
image1.CopyPixels(buffer1, stride1, 0);
image2.CopyPixels(buffer2, stride2, 0);
2023-08-18 17:44:33 +02:00
image = new WriteableBitmap(width1 + width2, height, 96, 96, format, null);
image.WritePixels(new Int32Rect(0, 0, width1, height), buffer1, stride1, 0);
image.WritePixels(new Int32Rect(width1, 0, width2, height), buffer2, stride2, 0);
image.Freeze();
2022-11-30 17:59:38 +01:00
}
return image;
}
}
}