Last active
April 7, 2019 06:48
-
-
Save kinex/b2c11e53473e53f7b207a919358d06ae to your computer and use it in GitHub Desktop.
Get JPEG image dimensions in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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