Skip to content

Instantly share code, notes, and snippets.

@kinex
Last active April 7, 2019 06:48
Show Gist options
  • Save kinex/b2c11e53473e53f7b207a919358d06ae to your computer and use it in GitHub Desktop.
Save kinex/b2c11e53473e53f7b207a919358d06ae to your computer and use it in GitHub Desktop.
Get JPEG image dimensions in Dart
// translated to Dart from a code snippet presented here:
// https://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java
Future<Size> getJpegDimensions(File jpegFile) async {
final f = await jpegFile.open();
Size dimension;
try {
// check for SOI marker
if (await f.readByte() != 255 || await f.readByte() != 216) {
throw new FormatException(
"SOI (Start Of Image) marker 0xff 0xd8 missing");
}
while (await f.readByte() == 255) {
int marker = await f.readByte();
int len = await f.readByte() << 8 | await f.readByte();
if (marker == 192) {
// skip one byte
await f.setPosition(await f.position() + 1);
final height = await f.readByte() << 8 | await f.readByte();
final width = await f.readByte() << 8 | await f.readByte();
dimension = Size(width.toDouble(), height.toDouble());
break;
}
// skip len - 2 bytes
await f.setPosition(await f.position() + len - 2);
}
} finally {
await f.close();
}
return dimension;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment