For JPEG usually yes, you can simply append zeros at the end and it won't affect the image itself. Both JFIF and EXIF (the two JPEG file formats) are immune to this. Some pedantic image processing tools may complain about extra data at the end, but they will be able to work with the image nonetheless.
As for PNG, I'm not familiar with its internal workings, but you can try appending zeros and simply see if it works. Most likely it's resilient enough too.
Details re: JPEG for curious readers.
JPEG is a compression algorithm, not a file format. There are two file formats that can house JPEG-compressed images: JFIF and EXIF (the latter one known for "EXIF tags" commonly used by cameras to store photo metadata). They are mostly compatible.
Both formats consist of a magic number
FF D8 followed by any number of binary blocks (called "segments"). Each block starts with a 4-byte marker:
- 1st byte is always
- 2nd byte is segment type identifier
- 3rd & 4th byte are a 16-bit number equal to segment data length in bytes + 2 (so 2 bytes less than cumulative length of a segment)
Segment header is followed by appropriate number of bytes. Subsequent segments are simply appended at the end.
JFIF and EXIF share identical structure and segment type identifiers, so they are "mostly" compatible. "Mostly", because they have different first segment requirements. In practice, most tools can deal with mixed JFIF/EXIF files, because those segments have different type identifiers.
All segments start with a
FF byte, so appending zeros creates invalid segments. Most tools seem to ignore these silently.