如何设置 UWP C# StorageFile 以将 SoftwareBitmap 存储到特定路径

Posted

技术标签:

【中文标题】如何设置 UWP C# StorageFile 以将 SoftwareBitmap 存储到特定路径【英文标题】:how to set up UWP C# StorageFile to store a SoftwareBitmap to a specific path 【发布时间】:2019-05-30 13:11:21 【问题描述】:

我正在尝试将 SoftwareBitmap 保存到文件中。

但是当我这样做时出现错误“参数不正确”: StorageFile.GetFileFromPathAsync()

这里是错误......。

pathname = "diag ProcessFrame .JPG"

网络摄像头 USB 框架的事件处理程序代码…………

        private void FrameReader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
    
        // Get frame image from camera:
        using (var frame = sender.TryAcquireLatestFrame())    //  ==>  MediaFrameReference 
        
            // Got image?
            if (frame != null)
            
                var renderer = _frameRenderers[frame.SourceKind];

                        renderer.ProcessFrame(frame);
            
        
    






    // Process latest frame received from USB webcam.
    public void ProcessFrame( MediaFrameReference frame)
    
        // Convert frame to a SoftwareBitmap of a valid format to display in an Image control:
            //      SoftwareBitmap Class
            //          https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.softwarebitmap?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(Windows.Graphics.Imaging.SoftwareBitmap)%3Bk(TargetFrameworkMoniker-.NETCore%2CVersion%3Dv5.0)%3Bk(DevLang-csharp)%26rd%3Dtrue
            var softwareBitmap = FrameRenderer.ConvertToDisplayableImage(frame?.VideoMediaFrame);



        if (softwareBitmap != null)
        
            // Swap the processed frame to _backBuffer and trigger UI thread to render it
            softwareBitmap = Interlocked.Exchange(ref _backBuffer, softwareBitmap);          // does bytes = h X w ?

            // UI thread always reset _backBuffer before using it.  Unused bitmap should be disposed.
            softwareBitmap?.Dispose();

            ////////////////////////   DISPLAY FRAME LOCALLY   /////////////////////////

            // Changes to xaml ImageElement must happen in UI thread through Dispatcher
            var task = _imageElement.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                async () =>
                
                    // Keep draining frames from the backbuffer until the backbuffer is empty.
                    SoftwareBitmap latest_frame_SoftwareBitmap;
                    while (( latest_frame_SoftwareBitmap = Interlocked.Exchange(ref _backBuffer, null)) != null)
                    
                                                         // Diag to save frame to a file:
                                                                 //VideoMediaFrame inputFrame    =     frame.VideoMediaFrame;
                                                                 //SoftwareBitmap  frame_SoftwareBitmap = inputFrame.SoftwareBitmap;

                                                                 Common.SaveSoftwareBitmapToFile( latest_frame_SoftwareBitmap, "diag ProcessFrame .JPG");

                    . . .

        





    // Saves encoded (ie. compressed) SoftwareBitmap image pixel data to a specific file pathname.
    public static async void SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap, String pathname)
    

        StorageFile outputFile = await StorageFile.GetFileFromPathAsync( pathname );
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  ERROR OCCURS HERE



        using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
        
            // Create an encoder with the desired format
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            // Set the software bitmap
            encoder.SetSoftwareBitmap(softwareBitmap);

            // Set additional encoding parameters, if needed
            //encoder.BitmapTransform.ScaledWidth = 320;
            //encoder.BitmapTransform.ScaledHeight = 240;
            //encoder.BitmapTransform.Rotation = Windows.Graphics.Imaging.BitmapRotation.Clockwise90Degrees;
            //encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
            encoder.IsThumbnailGenerated = true;

            try
            
                await encoder.FlushAsync();
            
            catch (Exception err)
            
                const int WINCODEC_ERR_UNSUPPORTEDOPERATION = unchecked((int)0x88982F81);
                switch (err.HResult)
                
                    case WINCODEC_ERR_UNSUPPORTEDOPERATION: 
                        // If the encoder does not support writing a thumbnail, then try again
                        // but disable thumbnail generation.
                        encoder.IsThumbnailGenerated = false;
                        break;
                    default:
                        throw;
                
            

            if (encoder.IsThumbnailGenerated == false)
            
                await encoder.FlushAsync();
            


        
    

【问题讨论】:

【参考方案1】:

来自StorageFile的文档:

参数异常

路径不能是相对路径或 Uri。查看 路径的值。

您需要指定文件的绝对路径。

无关说明:我会为您的文件尝试一些更好的命名约定。名称和扩展名之间的额外空间有点不合常规(并且可能会导致某些文件系统出现问题,例如基于 unix/linux 的操作系统上的 svn)。从上下文来看,像"C:/path/to/diagProcessFrame.jpg" 这样的文件名看起来确实不错。

【讨论】:

可能应该指出GetFileFromPathAsync 对于获取UWP 应用程序的隔离文件系统外部 文件的StorageFile 表示很有用。这在选择文件并且您想要制作副本时很有用

以上是关于如何设置 UWP C# StorageFile 以将 SoftwareBitmap 存储到特定路径的主要内容,如果未能解决你的问题,请参考以下文章

另一个进程错误正在使用 UWP StorageFile 文件

uwp StorageFile 没有得到简单的缩略图

如何在 UWP 视频 StorageFile 中保存 System.Media.DateEncoded

如何使 StorageFile.DisplayName getter 在 UWP 中系统地排除 FileType

你可以从它的路径访问一个选择的 StorageFile 吗? - UWP

如何在 UWP 中为 StorageFile 或 StorageFolder 获得具有 FILE_WRITE_ATTRIBUTES 访问权限的 Win32 HANDLE?