照片到Windows Phone 8.1中的Base64

时间:2015-02-21 13:07:45

标签: c# windows-runtime base64 windows-phone-8.1 writeablebitmap

我正在编写Windows Phone 8.1应用程序(WINPRT)。用户从图库中选择照片,此图像必须上传到服务器上。所以,我需要将它转换为Base64字符串。

所以,我关注Photo to Base64字符串的流程是: args.Files [0] > StorageFile > IRandomAccessStream > WriteableBitmap > pixelstream >的 base64string 但是图像可能非常大,所以我将其调整为48x48,然后将其转换为像素然后将其转换为字符串。

应用程序崩溃或手机卡在 Convert.ToBase64String(pixels);

我这样做错了吗?我还在将全尺寸图像的像素转换成转换吗?

   public async void ConvertPictureToBase64()
        {

            string ImageIntoBase64String = "";

            WriteableBitmap WriteableBitmapObject = new WriteableBitmap(1, 1);
            var storageStream = await StorageFileObject.OpenAsync(FileAccessMode.Read);
            IRandomAccessStream IRandomAccessStreamObject = await StorageFileObject.OpenReadAsync();
            WriteableBitmapObject.SetSource(IRandomAccessStreamObject);

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, storageStream);
            var pixelStream = WriteableBitmapObject.PixelBuffer.AsStream();
            var pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)WriteableBitmapObject.PixelWidth, (uint)WriteableBitmapObject.PixelHeight, 48, 48, pixels);

            ImageIntoBase64String = Convert.ToBase64String(pixels);
            await encoder.FlushAsync();    
        }

1 个答案:

答案 0 :(得分:1)

您可以使用我的方法压缩图像,然后将其转换为Base64字符串。

注意:我正在使用WriteableBitmapEx扩展类来调整图像大小。此外,WriteableBitmap类需要在UI线程上实例化,所以如果你在后台运行此方法就像我一样,你必须将引用传递给你所在的页面,这样方法当它使用WriteableBitmap类时,将能够使当前的UI调度程序工作。

这是:

public static async Task<String> ToCompressedBase64(this StorageFile imageFile, Page localPage)
{
    //Get the stream from the StorageFile
    IRandomAccessStream imageStream = await imageFile.OpenAsync(FileAccessMode.Read);

    System.Diagnostics.Debug.WriteLine("Original size ---> " + imageStream.ToFileSize());

    //Compresses the image if it exceedes the maximum file size
    imageStream.Seek(0);
    BitmapDecoder compressDecoder = await BitmapDecoder.CreateAsync(imageStream);
    PixelDataProvider compressionData = await compressDecoder.GetPixelDataAsync();
    byte[] compressionBytes = compressionData.DetachPixelData();

    //Set target compression quality
    BitmapPropertySet propertySet = new BitmapPropertySet();
    BitmapTypedValue qualityValue = new BitmapTypedValue(0.5, PropertyType.Single);
    propertySet.Add("ImageQuality", qualityValue);

    imageStream.Seek(0);
    imageStream = new InMemoryRandomAccessStream();
    BitmapEncoder compressionEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, imageStream, propertySet);
    compressionEncoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
                                    compressDecoder.PixelWidth, compressDecoder.PixelHeight,
                                    compressDecoder.DpiX, compressDecoder.DpiY, compressionBytes);
    await compressionEncoder.FlushAsync();

    //Create a BitmapDecoder from the stream
    BitmapDecoder resizeDecoder = await BitmapDecoder.CreateAsync(imageStream);
#if DEBUG
    System.Diagnostics.Debug.WriteLine("Old height and width ---> " + resizeDecoder.PixelHeight + " * " + resizeDecoder.PixelWidth + "\nCompressed size ---> " + imageStream.ToFileSize());
#endif
    //Resize the image if needed
    TaskCompletionSource<bool> completionSource = new TaskCompletionSource<bool>();
    localPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
    {
        const int maxImageWidth = 48;
        if (resizeDecoder.PixelWidth > maxImageWidth)
        {
            //Resize the image if it exceedes the maximum width
            int newHeight = (int)(maxImageWidth * resizeDecoder.PixelHeight / resizeDecoder.PixelWidth);
            WriteableBitmap tempBitmap = new WriteableBitmap((int)resizeDecoder.PixelWidth, (int)resizeDecoder.PixelHeight);
            imageStream.Seek(0);
            await tempBitmap.SetSourceAsync(imageStream);
            WriteableBitmap resizedImage = tempBitmap.Resize(maxImageWidth, newHeight, WriteableBitmapExtensions.Interpolation.Bilinear);

            //Assign to imageStream the resized WriteableBitmap
            InMemoryRandomAccessStream resizedStream = new InMemoryRandomAccessStream();
            await resizedImage.ToStream(resizedStream, BitmapEncoder.JpegEncoderId);
            imageStream = resizedStream;
        }
        completionSource.SetResult(true);
    }).Forget();
    await completionSource.Task;           

    //Converts the final image into a Base64 String
    imageStream.Seek(0);

    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);
    PixelDataProvider pixels = await decoder.GetPixelDataAsync();
#if DEBUG
    System.Diagnostics.Debug.WriteLine("New height and width ---> " + decoder.PixelHeight + " * " + decoder.PixelWidth + "\nSize after resize ---> " + imageStream.ToFileSize());
#endif
    byte[] bytes = pixels.DetachPixelData();

    //Encode image
    InMemoryRandomAccessStream encoded = new InMemoryRandomAccessStream();
    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, encoded);
    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, decoder.PixelWidth, decoder.PixelHeight, decoder.DpiX, decoder.DpiY, bytes);
    await encoder.FlushAsync();
    encoded.Seek(0);

    //Read bytes
    byte[] outBytes = new byte[encoded.Size];
    await encoded.AsStream().ReadAsync(outBytes, 0, outBytes.Length);

    //Create Base64
    return Convert.ToBase64String(outBytes);
}

注意:我正在使用TaskCompletionSource而不是等待页面调度程序上的RunAsync调用,因为如果使用异步操作调用它,则实际上无法等待它,因为它返回一个调用者的任务和该方法返回它而不等待Action完成。 所以我最终得到了内部异步Action,它在控件进入main方法之后仍在运行。 使用TaskCompletionSource并等待它解决了这个问题:)

Forget方法只是一种方法,我必须在异步方法中调用异步方法而不等待它时抑制VS警告。

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Forget(this IAsyncAction action) { }

您可以这样称呼它:

Task<String> base64ResizedImage = Task.Run(async () => await args.Files[0].ToCompressedBase64(this));

另外,如果图像的宽度超出给定值,我的方法会调整图像大小(我在你的问题中设置了48)。 如果你想检查高度,只需编辑该部分并检查图像边界:)