Как нарисовать изображение в SharpDX из Интернета в универсальном приложении?

Я хочу нарисовать изображение из Интернета в универсальном приложении для Windows 8 в SharpDX. Как часть приложения, которое я создаю, я должен динамически загружать изображения из Интернета на основе URL-адреса, введенного пользователем.

Здесь задают аналогичный вопрос, но он использует System.Drawing, который недоступен в универсальном приложении Windows 8.

Я взломал что-то вместе, чтобы начать, но ничего не рисуется, когда я звоню DeviceContext.DrawBitmap, И нет никаких исключений.

public static async Bitmap1 DownloadRemoteImageFile(string url, DeviceContext context)
{
    using (var client = new HttpClient())
    {
        var uri = new Uri(url);

        var response = await client.GetInputStreamAsync(uri);

        var stream = response.AsStreamForRead();

        var size = new Size2(1121, 631); // not sure of the size here, so these are testing values
        var bitmapProperties = new BitmapProperties1(new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
        var dataStream = new DataStream(100000, true, true); // not sure how to get the size here, so 100000 is for testing
        stream.CopyTo(dataStream);
        return new Bitmap1(context, size, dataStream, 1, bitmapProperties);
    }
}

1 ответ

Решение

Вот код, который я написал для универсального приложения, для чтения изображения (PNG, JPEG, ...) из потока и получения доступа к необработанным битам. Код в VB, но должно быть очевидно, как сделать то же самое в C#...

' The stream might be from file.OpenAsync, or might come from anything else
' First job is to load the bitmap
Dim decoder As BitmapDecoder = Await BitmapDecoder.CreateAsync(stream)
Dim frame As BitmapFrame = Await decoder.GetFrameAsync(0)
Dim width = CInt(decoder.OrientedPixelWidth)
Dim height = CInt(decoder.OrientedPixelHeight)
Dim isflipped = (decoder.OrientedPixelWidth = decoder.PixelHeight AndAlso decoder.OrientedPixelHeight = decoder.PixelWidth)

' Some bitmaps e.g. from the camera are flipped. This code
' orients them the right way. Also, if I wanted to scale
' width/height, then this transform would do the scalingtoo.
Dim xform As New BitmapTransform With {
    .InterpolationMode = BitmapInterpolationMode.NearestNeighbor,
    .ScaledWidth = CUInt(If(isflipped, height, width)),
    .ScaledHeight = CUInt(If(isflipped, width, height)),
    .Bounds = New BitmapBounds With {.X = 0, .Y = 0, .Width = CUInt(width), .Height = CUInt(height)}}

' Now we can get the raw pixel data
Dim pixels = Await frame.GetPixelDataAsync(
    BitmapPixelFormat.Rgba8,
    BitmapAlphaMode.Premultiplied,
    xform,
    ExifOrientationMode.RespectExifOrientation,
    ColorManagementMode.DoNotColorManage)

Dim src = pixels.DetachPixelData()
Dim scanlines = CInt(height)

' What shall we do with the raw bitmap data? It's up to us.
' In my case I saved it into a small helper class I wrote
' called "MutableBitmapInfo" for use by subsequent
' manipulation and SharpDX image construction.
Dim mbi As New MutableBitmapInfo()
mbi._bitmap = New WriteableBitmap(width, scanlines)
Using dst = mbi.LockPixels()
    For i = 0 To width * scanlines * 4 - 1 Step 4
        Const RED = 0, GREEN = 1, BLUE = 2, ALPHA = 3
        dst.Stream.WriteByte(src(i + BLUE))
        dst.Stream.WriteByte(src(i + GREEN))
        dst.Stream.WriteByte(src(i + RED))
        dst.Stream.WriteByte(src(i + ALPHA))
    Next
End Using
Другие вопросы по тегам