Search code examples
c#asp.netfile-uploadexif

What is the best way to remove Exif data from Images while uploading in c#


What is the best way to remove Exif data from Images while uploading in c# ? I tried the solution given in : https://www.techmikael.com/2009/07/removing-exif-data-continued.html

But the problem I am facing is that after saving the output stream which comes from the above solution, the Image is not readable. It removes Exif info from the file. But I am not able to view the image later.

Can anyone help me here ?

Below is my code:

    protected void SaveFile()
    {
        try
        {
            JpegPatcher _jpegPatcher = new JpegPatcher();
            System.IO.Stream stream = new System.IO.MemoryStream();
            //Get stream data of uploaded file
            Stream checkStream = fileUpload.PostedFile.InputStream;
            //Pass the stream to remove Exif info
            Stream outStream1 = _jpegPatcher.PatchAwayExif(checkStream, stream);

            //Save the file
            string Fpath = Path.Combine(path, fileUpload.FileName);
            using (FileStream outputFileStream = new FileStream(Fpath, FileMode.Create, FileAccess.Write))
            {
                stream.Position = 0;
                stream.CopyTo(outputFileStream);
                stream.Flush();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Solution

  • Does this help, and simplifying. Remember to ensure position is 0 on the input stream when you start reading.

            JpegPatcher _jpegPatcher = new JpegPatcher();
            //Get stream data of uploaded file
            Stream checkStream = fileUpload.PostedFile.InputStream;
            checkStream.Position = 0; // Reset position
            //Pass the stream to remove Exif info
            //Save the file
            string Fpath = Path.Combine(path, fileUpload.FileName);
            using (FileStream outputFileStream = new FileStream(Fpath, FileMode.Create, FileAccess.Write))
            {
                _jpegPatcher.PatchAwayExif(checkStream, outputFileStream);
            }