Easy way to clean metadata from an image?

倖福魔咒の 提交于 2019-12-04 19:39:41

Metadata - Gets or sets the metadata that will be associated with this bitmap during encoding.

  • The 'Oops, I (not so accidentally) forgot something way: Open the original bitmap file into a System.drawing.Bitmap object. Clone it to a new Bitmap object. Write the clone's contents to a new file. Like this one-liner:

    ((System.Drawing.Bitmap)System.Drawing.Image.FromFile(@"C:\file.png").Clone()).Save(@"C:\file-nometa.png");

  • The direct file manipulation way (only for JPEG): Blog post about removing the EXIF area.

I would suggest this, the source is here: Removing Exif-Data for jpg file

Changing a bit the 1st function

public Stream PatchAwayExif(Stream inStream)
{
  Stream outStream = new MemoryStream();
  byte[] jpegHeader = new byte[2];
  jpegHeader[0] = (byte)inStream.ReadByte();
  jpegHeader[1] = (byte)inStream.ReadByte();
  if (jpegHeader[0] == 0xff && jpegHeader[1] == 0xd8) //check if it's a jpeg          file
  {
     SkipAppHeaderSection(inStream);
  }
  outStream.WriteByte(0xff);
  outStream.WriteByte(0xd8);

  int readCount;
  byte[] readBuffer = new byte[4096];
  while ((readCount = inStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  outStream.Write(readBuffer, 0, readCount);

  return outStream;
}

And the second function with no changes, as post

    private void SkipAppHeaderSection(Stream inStream)
    {
        byte[] header = new byte[2];
        header[0] = (byte)inStream.ReadByte();
        header[1] = (byte)inStream.ReadByte();

        while (header[0] == 0xff && (header[1] >= 0xe0 && header[1] <= 0xef))
        {
            int exifLength = inStream.ReadByte();
            exifLength = exifLength << 8;
            exifLength |= inStream.ReadByte();

            for (int i = 0; i < exifLength - 2; i++)
            {
                inStream.ReadByte();
            }
            header[0] = (byte)inStream.ReadByte();
            header[1] = (byte)inStream.ReadByte();
        }
        inStream.Position -= 2; //skip back two bytes
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!