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

82 lines
2.6 KiB
C#
Raw Normal View History

2024-05-19 23:23:27 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// Copyright © 2024 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.IO;
using System.Threading.Tasks;
namespace MapControl
{
public static partial class ImageLoader
{
public static IImage LoadImage(Uri uri)
{
return null;
}
public static IImage LoadImage(Stream stream)
{
return new Bitmap(stream);
}
public static Task<IImage> LoadImageAsync(Stream stream)
{
return Task.FromResult(LoadImage(stream));
}
public static Task<IImage> LoadImageAsync(string path)
{
2024-05-22 16:15:29 +02:00
if (!File.Exists(path))
2024-05-19 23:23:27 +02:00
{
2024-05-22 16:15:29 +02:00
return Task.FromResult<IImage>(null);
}
2024-05-19 23:23:27 +02:00
2024-05-22 16:15:29 +02:00
return Task.Run(() =>
{
2024-05-19 23:23:27 +02:00
using var stream = File.OpenRead(path);
return LoadImage(stream);
});
}
2024-05-21 23:18:00 +02:00
2024-05-22 16:15:29 +02:00
internal static async Task<IImage> LoadMergedImageAsync(Uri uri1, Uri uri2, IProgress<double> progress)
2024-05-21 23:18:00 +02:00
{
2025-01-01 18:20:33 +01:00
WriteableBitmap mergedImage = null;
2024-05-22 16:15:29 +02:00
2025-01-01 18:20:33 +01:00
var images = await LoadImagesAsync(uri1, uri2, progress);
2024-05-22 16:15:29 +02:00
if (images.Length == 2 &&
images[0] is Bitmap image1 &&
images[1] is Bitmap image2 &&
image1.PixelSize.Height == image2.PixelSize.Height &&
image1.Format.HasValue &&
2024-05-22 16:45:34 +02:00
image1.Format == image2.Format &&
2024-05-22 16:15:29 +02:00
image1.AlphaFormat.HasValue &&
2024-05-22 16:45:34 +02:00
image1.AlphaFormat == image2.AlphaFormat)
2024-05-22 16:15:29 +02:00
{
var bpp = image1.Format.Value == PixelFormat.Rgb565 ? 2 : 4;
2024-05-22 16:45:34 +02:00
var pixelSize = new PixelSize(image1.PixelSize.Width + image2.PixelSize.Width, image1.PixelSize.Height);
var stride1 = bpp * image1.PixelSize.Width;
var stride = bpp * pixelSize.Width;
var bufferSize = stride * pixelSize.Height;
2024-05-22 16:15:29 +02:00
unsafe
{
2024-05-22 16:45:34 +02:00
fixed (byte* ptr = new byte[stride * pixelSize.Height])
2024-05-22 16:15:29 +02:00
{
2024-05-22 16:45:34 +02:00
var buffer = (nint)ptr;
2024-05-22 16:15:29 +02:00
2024-05-22 16:45:34 +02:00
image1.CopyPixels(new PixelRect(image1.PixelSize), buffer, bufferSize, stride);
image2.CopyPixels(new PixelRect(image2.PixelSize), buffer + stride1, bufferSize, stride);
2024-05-22 16:15:29 +02:00
2025-01-01 18:20:33 +01:00
mergedImage = new WriteableBitmap(image1.Format.Value, image1.AlphaFormat.Value, buffer, pixelSize, image1.Dpi, stride);
2024-05-22 16:15:29 +02:00
}
}
}
2025-01-01 18:20:33 +01:00
return mergedImage;
2024-05-21 23:18:00 +02:00
}
2024-05-19 23:23:27 +02:00
}
}