feat: Add metadata removal functionality

This commit is contained in:
Teacup
2025-08-08 17:13:36 -07:00
committed by Natsumi
parent 0fb3f2fbb7
commit 06e06a7164
4 changed files with 118 additions and 2 deletions

View File

@@ -27,6 +27,11 @@ public class PNGFile : IDisposable
{
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 4096);
}
public PNGFile(string filePath, int bufferSize)
{
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, bufferSize);
}
/// <summary>
/// Retrieves the first PNG chunk of the specified type from the file, or null if none were found.
@@ -106,7 +111,57 @@ public class PNGFile : IDisposable
return true;
}
/// <summary>
/// Deletes a PNG chunk from the file.
/// </summary>
/// <param name="chunk">The PNG chunk to delete. Needs a valid index set.</param>
/// <returns>True if the chunk was successfully deleted, otherwise false.</returns>
public bool DeleteChunk(PNGChunk chunk)
{
if (!chunk.ExistsInFile(fileStream))
return false;
int bufferSize = 128 * 1024;
int deleteStart = chunk.Index;
int deleteLength = chunk.Length + CHUNK_NONDATA_SIZE;
long sourcePos = deleteStart + deleteLength;
long destPos = deleteStart;
byte[] buffer = new byte[bufferSize];
// Copy everything after the deleted section forward
while (sourcePos < fileStream.Length)
{
fileStream.Seek(sourcePos, SeekOrigin.Begin);
int bytesRead = fileStream.Read(buffer, 0, Math.Min(buffer.Length, (int)(fileStream.Length - sourcePos)));
if (bytesRead == 0)
break;
fileStream.Seek(destPos, SeekOrigin.Begin);
fileStream.Write(buffer, 0, bytesRead);
sourcePos += bytesRead;
destPos += bytesRead;
}
fileStream.SetLength(fileStream.Length - deleteLength);
metadataChunkCache.Remove(chunk);
// update the index of all cached chunks
for (int i = 0; i < metadataChunkCache.Count; i++)
{
var cachedChunk = metadataChunkCache[i];
if (cachedChunk.Index > deleteStart)
cachedChunk.Index -= deleteLength;
}
return true;
}
/// <summary>
/// Retrieves all PNG metadata chunks of a specified type
/// </summary>