Search code examples
c#imagesavekinectkinect-sdk

Why is my program not saving images?


I have a program where Kinect gets a image and saves it, to a location the user specifies. I know the program finds the right folders since it creates more folders to save different kinds of images in, and those folders will be created. My current code (below) for saving the image works for other programs, so is there some parameter that is stopping it I am not aware of? Thanks in advance.

Saving the Image

using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
    if (colorFrame == null)
    {
        return;
    }

    byte[] pixels = new byte[sensor.ColorStream.FramePixelDataLength];

    //WriteableBitmap image = new WriteableBitmap(
    //     sensor.ColorStream.FrameWidth,
    //     sensor.ColorStream.FrameHeight, 96, 96,
    //     PixelFormats.Bgra32, null);

    colorFrame.CopyPixelDataTo(pixels);

    colorImage.WritePixels(new Int32Rect(0, 0, colorImage.PixelWidth,
                                         colorImage.PixelHeight),
                           pixels, colorImage.PixelWidth * 4, 0);
    //BitmapSource image = BitmapSource.Create(colorFrame.Width, colorFrame.Height,
    //                                         96, 96, PixelFormats.Bgr32, null,
    //                                         pixels, colorFrame.Width * 4);

    //image.WritePixels(new Int32Rect(0, 0, image.PixelWidth, image.PixelHeight),
    //                  pixels, image.PixelWidth * sizeof(int), 0);

    //video.Source = image;

    totalFrames++;
    BitmapEncoder encoder = new JpegBitmapEncoder();

    encoder.Frames.Add(BitmapFrame.Create(colorImage));

    //path = System.IO.Path.Combine("C:/", "Kinected", "Images");

    if (PersonDetected == true)
    {
        if (totalFrames % 10 == 0)
        {
            if (file_name != null && colorImage != null)
            {
                try
                {
                    using (FileStream fs = new FileStream(colorPath +
                           @"\Kinected Image " + time + ".jpg", FileMode.Create))
                    {
                        encoder.Save(fs);
                    }
                }
                catch (IOException)
                {
                    System.Windows.MessageBox.Show("Save Failed");
                }
            }
        }

        skeletonDeLbl.Content = "Skeleton Detected!";
    }

    if (PersonDetected == false) skeletonDeLbl.Content = "No Skeleton Detected.";
}

Determining the Path

FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description =
    "Select which folder you want Kinected to keep all of its information/images in.";
DialogResult result = dialog.ShowDialog();

colorPath = dialog.SelectedPath + @"\Color Images";
depthPath = dialog.SelectedPath + @"\Depth Images";
facePath = dialog.SelectedPath + @"\Face Data";

if (!Directory.Exists(colorPath))
    Directory.CreateDirectory(colorPath);
if (!Directory.Exists(depthPath))
    Directory.CreateDirectory(depthPath);
if (!Directory.Exists(facePath))
    Directory.CreateDirectory(facePath);

System.Windows.MessageBox.Show(colorPath);

EDIT

Turns out file_name was just null, but now I am getting the error when it gets to the line using (FileStream fs = new FilesStream(file_name, FileMode.Create)) it says:

An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll

Additional information: The given path's format is not supported.

Why is this happening? I am using the exact same code as Microsoft's demo, and it works fine there. Thanks.


Solution

  • You should use the following code to combine strings into a path

    colorPath = System.IO.Path.Combine(dialog.SelectedPath, "Color Images");
    

    The Combine method takes care of adding or removing backslashes where necessary.


    And don't forget to use the debugger. You can set breakpoints and inspect the variables and do many more things.

    The debugger is your best friend!


    UPDATE

    You are also using invalid characters in the filename. This method replaces invalid characters and applies also some other fixes to a filename

    /// <summary>
    ///   Replaces invalid characters in a file name by " ". Apply only to the filename.ext
    ///   part, not to the path part.
    /// </summary>
    /// <param name="fileName">A file name (not containing the path part) possibly
    ///   containing invalid characters.</param>
    /// <returns>A valid file name.</returns>
    public static string GetValidFileName(string fileName)
    {
        string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
        string s = Regex.Replace(fileName, "[" + invalidChars + "]", " ");
        s = Regex.Replace(s, @"\s\s+", " "); // Replace multiple spaces by one space.
        string fil = Path.GetFileNameWithoutExtension(s).Trim().Trim('.');
        string ext = Path.GetExtension(s).Trim().Trim('.');
        if (ext != "") {
            fil += "." + ext;
        }
        fil = fil.Replace(" .", ".");
        return fil == "." ? "" : fil;
    }