Windows Phone 8.1如何关闭StorageFile?

时间:2016-06-15 10:54:48

标签: c# image file windows-phone-8.1

我有一点问题。我使用StorageFile使用grayScale过滤器创建图像。当我尝试在第二个图像上设置过滤器时,问题就开始了。我第一次拍照并设置过滤器和它的确定,第二次当我拍照并尝试设置过滤器时我收到错误消息:Access is denied. Exception from HRESULT: ...。第三次当我拍照时,我可以设置过滤器,第四次我再次出错,依此类推。我知道问题是app仍然使用相同的StorageFile并且它已锁定,但我不知道如何关闭该文件。

这里我创建了StorageFile文件:

async private void Capture_Photo_Click(object sender, RoutedEventArgs e)
{
    ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
    InMemoryRandomAccessStream imageStream = new InMemoryRandomAccessStream();
    await newCapture.CapturePhotoToStreamAsync(imgFormat, imageStream);
    BitmapDecoder dec = await BitmapDecoder.CreateAsync(imageStream);
    BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(imageStream, dec);
    string currentorientation = DisplayInformation.GetForCurrentView().CurrentOrientation.ToString();
    switch (currentorientation)
    {
        case "Landscape":
            enc.BitmapTransform.Rotation = BitmapRotation.None;
            break;
        case "Portrait":
            enc.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;
            break;
        case "LandscapeFlipped":
            enc.BitmapTransform.Rotation = BitmapRotation.Clockwise180Degrees;
            break;
        case "PortraitFlipped":
            enc.BitmapTransform.Rotation = BitmapRotation.Clockwise270Degrees;
            break;
        default:
            enc.BitmapTransform.Rotation = BitmapRotation.None;
            break;
    }
    await enc.FlushAsync();
    string naziv = "IMG_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
    naziv = naziv.Insert(12, "_");
    file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
        naziv,
        CreationCollisionOption.ReplaceExisting);
    var filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
    await RandomAccessStream.CopyAsync(imageStream, filestream);
    BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));
    var obj = App.Current as App;
    obj.fileTransfer = file;
    obj.ImageToEdit = bmpImage;
    await newCapture.StopPreviewAsync();
    bmpImage = null;
    await imageStream.FlushAsync();
    await filestream.FlushAsync();
    Frame.Navigate(typeof(EditImage));
}

这是grayScale过滤器:

 private async void ConvertToGrayScale()
{

    var obj = App.Current as App;
    StorageFile file = obj.fileTransfer;
    try {
        if (obj.isCrooped == true && obj.writebleImg != null) {
            file = await WriteableBitmapToStorageFile(obj.writebleImg);
        }
        else {
            file = obj.fileTransfer;
        }
        BitmapDecoder decoder = null;

        using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
        {
            decoder = await BitmapDecoder.CreateAsync(stream);

            // Get the first frame
            BitmapFrame bitmapFrame = await decoder.GetFrameAsync(0);

            // Save the resolution (will be used for saving the file later)
            //dpiX = bitmapFrame.DpiX;
            //dpiY = bitmapFrame.DpiY;

            // Get the pixels
            PixelDataProvider dataProvider =
                await bitmapFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                    BitmapAlphaMode.Premultiplied,
                                                    new BitmapTransform(),
                                                    ExifOrientationMode.RespectExifOrientation,
                                                    ColorManagementMode.ColorManageToSRgb);

            byte[] pixels = dataProvider.DetachPixelData();

            // Create WriteableBitmap and set the pixels
            WriteableBitmap srcBitmap = new WriteableBitmap((int)bitmapFrame.PixelWidth,
                                                         (int)bitmapFrame.PixelHeight);

            using (Stream pixelStream = srcBitmap.PixelBuffer.AsStream())
            {
                await pixelStream.WriteAsync(pixels, 0, pixels.Length);
            }


            byte[] srcPixels = new byte[4 * srcBitmap.PixelWidth * srcBitmap.PixelHeight];

            using (Stream pixelStream = srcBitmap.PixelBuffer.AsStream())
            {
                await pixelStream.ReadAsync(srcPixels, 0, srcPixels.Length);
            }

            // Create a destination bitmap and pixels array
            WriteableBitmap dstBitmap =
                    new WriteableBitmap(srcBitmap.PixelWidth, srcBitmap.PixelHeight);
            byte[] dstPixels = new byte[4 * dstBitmap.PixelWidth * dstBitmap.PixelHeight];


            for (int i = 0; i < srcPixels.Length; i += 4)
            {
                double b = (double)srcPixels[i] / 255.0;
                double g = (double)srcPixels[i + 1] / 255.0;
                double r = (double)srcPixels[i + 2] / 255.0;

                byte a = srcPixels[i + 3];

                double e = (0.21 * r + 0.71 * g + 0.07 * b) * 255;
                byte f = Convert.ToByte(e);

                dstPixels[i] = f;
                dstPixels[i + 1] = f;
                dstPixels[i + 2] = f;
                dstPixels[i + 3] = a;

            }

            // Move the pixels into the destination bitmap
            using (Stream pixelStream = dstBitmap.PixelBuffer.AsStream())
            {
                await pixelStream.WriteAsync(dstPixels, 0, dstPixels.Length);
            }
            dstBitmap.Invalidate();

            // Display the new bitmap
            ImagePreview.Source = dstBitmap;

        }

    }
    catch (Exception err) { 
    err.StackTrace.ToString(); 
    }
}

在这一行我得到了错误:

using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())

1 个答案:

答案 0 :(得分:0)

您需要在撰写数据后立即关闭filestream

using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    await RandomAccessStream.CopyAsync(imageStream, filestream);
}