Redth / ResizetizerNT

Add SVG's and PNG's to your shared Xamarin Project
MIT License
318 stars 31 forks source link

How to read the resized file from the assembly? #61

Open eltomek opened 3 years ago

eltomek commented 3 years ago

For the purpose of using the Mapsui library I need to be able to read the compiled resource from the assembly (see the example https://github.com/Mapsui/Mapsui/blob/af2bf64d3f45c0a3a7b91d2d58cc2a4fff3d13d3/Tests/Mapsui.Tests.Common/Maps/BitmapSymbolSample.cs#L67).

This method works for resources with Embedded resource build action but with ResizetizerNT it's not the case. Does the resized file become part of the assembly? If so, is there any way to access it with the generic name (picture.png instead of picture.scale-100.png)?

Feroks commented 3 years ago

In case you have not found solution yet. Here is how I did it.

Android

public Stream GetStream(FileImageSource source)
{
    var context = Platform.AppContext;
    var id = context.GetDrawableId(source);
    return GetDrawableStream(id, context);
}

private static Stream GetDrawableStream(int id, Context context)
{
    var ms = new MemoryStream();

    using var bitmap = BitmapFactory.DecodeResource(context.Resources, id);
    bitmap.Compress(Bitmap.CompressFormat.Png, 0, ms);

    return ms;
}

UWP

public async Task<Stream> GetStreamAsync(FileImageSource source)
{
    var uri = new Uri($"ms-appx:///{source.File}");

    try
    {
        var storageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);
        return await storageFile.OpenStreamForReadAsync();
    }
    catch (FileNotFoundException)
    {
        return null;
    }
}