Giter Site home page Giter Site logo

dart_image_size_getter's Introduction

image_size_getter

Do not completely decode the image file, just read the metadata to get the image width and height.

Just support jpeg, gif, png, webp, bmp.

Usage

Image of File

import 'dart:io';

import 'package:image_size_getter/image_size_getter.dart';
import 'package:image_size_getter/file_input.dart'; // For compatibility with flutter web.

void main(List<String> arguments) async {
  final file = File('asset/IMG_20180908_080245.jpg');
  final size = ImageSizeGetter.getSize(FileInput(file));
  print('jpg = $size');

  final pngFile = File('asset/ic_launcher.png');
  final pngSize = ImageSizeGetter.getSize(FileInput(pngFile));
  print('png = $pngSize');

  final webpFile = File('asset/demo.webp');
  final webpSize = ImageSizeGetter.getSize(FileInput(webpFile));
  print('webp = $webpSize');

  final gifFile = File('asset/dialog.gif');
  final gifSize = ImageSizeGetter.getSize(FileInput(gifFile));
  print('gif = $gifSize');
}

Image of Memory

import 'package:image_size_getter/image_size_getter.dart';

void foo(Uint8List image){
  final memoryImageSize = ImageSizeGetter.getSize(MemoryInput(image));
  print('memoryImageSize = $memoryImageSize');
}

Image of Http

See HttpInput.

About Size

The size contains width and height.

But some image have orientation. Such as jpeg, when the orientation of exif is 5, 6, 7 or 8, the width and height will be swapped.

We can use next code to get width and height.

void foo(File file) {
  final size = ImageSizeGetter.getSize(FileInput(file));
  if (size.needRotate) {
    final width = size.height;
    final height = size.width;
    print('width = $width, height = $height');
  } else {
    print('width = ${size.width}, height = ${size.height}');
  }
}

AsyncImageInput

If your data source is read asynchronously, consider using AsyncImageInput.

A typical use case is http_input.

Custom

We can implement our own input or decoder.

In addition to several built-in implementations, subsequent implementations will also be added to the project through plugin.

Custom Input

Such as: http_input.

In addition, if your picture has verification, for example, you need to use the request header to access it, or you need a post request to get it, you need to customize input.

Custom Decoder

Such as bmp decoder

Check the file type:

VPMMfA

The width and height:

AZnx9I

So, we can write code with:

import 'package:image_size_getter/image_size_getter.dart';

class BmpDecoder extends BaseDecoder {
  const BmpDecoder();

  @override
  String get decoderName => 'bmp';

  @override
  Size getSize(ImageInput input) {
    final widthList = input.getRange(0x12, 0x16);
    final heightList = input.getRange(0x16, 0x1a);

    final width = convertRadix16ToInt(widthList, reverse: true);
    final height = convertRadix16ToInt(heightList, reverse: true);
    return Size(width, height);
  }

  @override
  Future<Size> getSizeAsync(AsyncImageInput input) async {
    final widthList = await input.getRange(0x12, 0x16);
    final heightList = await input.getRange(0x16, 0x1a);

    final width = convertRadix16ToInt(widthList, reverse: true);
    final height = convertRadix16ToInt(heightList, reverse: true);
    return Size(width, height);
  }

  @override
  bool isValid(ImageInput input) {
    final list = input.getRange(0, 2);
    return _isBmp(list);
  }

  @override
  Future<bool> isValidAsync(AsyncImageInput input) async {
    final list = await input.getRange(0, 2);
    return _isBmp(list);
  }

  bool _isBmp(List<int> startList) {
    return startList[0] == 66 && startList[1] == 77;
  }
}

Use it:

final bmp = File('../../example/asset/demo.bmp');

const BmpDecoder decoder = BmpDecoder();
final input = FileInput(bmp);

assert(decoder.isValid(input));
expect(decoder.getSize(input), Size(256, 256));

Register custom decoder to image size getter

ImageSizeGetter.registerDecoder(const BmpDecoder());

The method can also be used to replace the default decoder.

For example, you think the existing JPEG format is not rigorous enough.

ImageSizeGetter.registerDecoder(const MyJpegDecoder());

Use decoder alone

Each decoder can be used alone.

void decodeWithImageInput(ImageInput input) {
  BaseDecoder decoder = const GifDecoder();
  final isGif = decoder.isValid(input);
  print('isGif: $isGif');

  if (isGif) {
    final size = decoder.getSize(input);
    print('size: $size');
  }
}

void decodeWithAsyncImageInput(AsyncImageInput input) async {
  BaseDecoder decoder = const PngDecoder();
  final isPng = await decoder.isValidAsync(input);
  print('isPng: $isPng');

  if (isPng) {
    final size = await decoder.getSizeAsync(input);
    print('size: $size');
  }
}

migrate

See migrate

Other question

The package is dart package, no just flutter package. So, if you want to get flutter asset image size, you must convert it to memory(Uint8List).

final buffer = await rootBundle.load('assets/logo.png'); // get the byte buffer
final memoryImageSize = ImageSizeGetter.getSize(MemoryInput.byteBuffer(buffer));
print('memoryImageSize = $memoryImageSize');

LICENSE

Apache 2.0

dart_image_size_getter's People

Contributors

caijinglong avatar jiachenren avatar nkming2 avatar poppingmoon avatar zalithka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

dart_image_size_getter's Issues

获取宽高相反

iOS拍照后的照片,得到图片的宽高值是相反的。比如说下面的图片。正常是3024×4032,但是 ImageSizGetter.getSize(file)得到后是 4032x3024
1

Jpg orientation is not taken into account

Hello and thank you for the nice plugin.

I tried to read some jpg files and the reported width and height was wrong in files that have the 'Right-Top' orientation.

I decoded the image headers via ImageMagick. Do you need any additional information?

Correct read:

Image:
  Filename: IMG_1697.JPG
  Format: JPEG (Joint Photographic Experts Group JFIF format)
  Mime type: image/jpeg
  Class: DirectClass
  Geometry: 4000x3000+0+0
  Resolution: 180x180
  Print size: 22.2222x16.6667
  Units: PixelsPerInch
  Colorspace: sRGB
  Type: TrueColor
  Base type: Undefined
  Endianness: Undefined
  Depth: 8-bit
  Channel depth:
    red: 8-bit
    green: 8-bit
    blue: 8-bit
  Rendering intent: Perceptual
  Gamma: 0.454545
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Background color: white
  Border color: srgb(223,223,223)
  Matte color: grey74
  Transparent color: black
  Interlace: None
  Intensity: Undefined
  Compose: Over
  Page geometry: 4000x3000+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: JPEG
  Quality: 90
  Orientation: TopLeft

Read wrongly:

Image:
  Filename: IMG_1690.JPG
  Format: JPEG (Joint Photographic Experts Group JFIF format)
  Mime type: image/jpeg
  Class: DirectClass
  Geometry: 4000x3000+0+0
  Resolution: 180x180
  Print size: 22.2222x16.6667
  Units: PixelsPerInch
  Colorspace: sRGB
  Type: TrueColor
  Base type: Undefined
  Endianness: Undefined
  Depth: 8-bit
  Channel depth:
    red: 8-bit
    green: 8-bit
    blue: 8-bit
  Rendering intent: Perceptual
  Gamma: 0.454545
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Background color: white
  Border color: srgb(223,223,223)
  Matte color: grey74
  Transparent color: black
  Interlace: None
  Intensity: Undefined
  Compose: Over
  Page geometry: 4000x3000+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: JPEG
  Quality: 90
  Orientation: RightTop

[Bug report] Lossless WebP Size is not correct

Version

2.1.2

Platforms

dart

Device Model

any

flutter info

[√] Flutter (Channel stable, 3.19.4, on Microsoft Windows [Version 10.0.22631.3296], locale ja-JP)
    • Flutter version 3.19.4 on channel stable at C:\Users\thkt3\fvm\versions\stable
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 68bfaea224 (10 days ago), 2024-03-20 15:36:31 -0700
    • Engine revision a5c24f538d
    • Dart version 3.3.2
    • DevTools version 2.31.1

[√] Windows Version (Installed version of Windows is version 10 or higher)

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at C:\Users\thkt3\AppData\Local\Android\sdk
    • Platform android-34, build-tools 33.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jbr\bin\java
    • Java version OpenJDK Runtime Environment (build 17.0.7+0-b2043.56-10550314)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Visual Studio - develop Windows apps (Visual Studio Build Tools 2022 17.9.2)
    • Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools
    • Visual Studio Build Tools 2022 version 17.9.34622.214
    • Windows 10 SDK version 10.0.22000.0

[√] Android Studio (version 2023.1)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.7+0-b2043.56-10550314)

[√] VS Code (version 1.87.2)
    • VS Code at C:\Users\thkt3\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.84.0

[√] Connected device (4 available)
    • Pixel 7a (mobile) • 192.168.151.7:40979 • android-arm64  • Android 14 (API 34)
    • Windows (desktop) • windows             • windows-x64    • Microsoft Windows [Version 10.0.22631.3296]
    • Chrome (web)      • chrome              • web-javascript • Google Chrome 123.0.6312.60
    • Edge (web)        • edge                • web-javascript • Microsoft Edge 123.0.2420.65

[√] Network resources
    • All expected network resources are available.

• No issues found!

How to reproduce?

Getting size of lossless WebP using ImageSizeGetter.getSize() returns irrelevant value.

For example, with https://raw.githubusercontent.com/poppingmoon/dart_image_size_getter/webp-lossless/example/asset/demo_lossless.webp as input, ImageSizeGetter.getSize() returns Size( 19512, 18715, needRotate: false ), which is different from actual size (988, 466).

Logs

No response

Example code (optional)

No response

Contact

No response

[Bug report] Unrecognised JPEG File from Gallery on Android

Version

2.1.2

Platforms

Android

Device Model

Samsung Galaxy A10

flutter info

$ flutter doctor -v
[√] Flutter (Channel stable, 3.13.9, on Microsoft Windows [version 10.0.22621.2428], locale fr-FR)
    • Flutter version 3.13.9 on channel stable at C:\Users\pnv_fch.NUC_PNV_FCH\fvm\versions\3.13.3
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision d211f42860 (3 weeks ago), 2023-10-25 13:42:25 -0700
    • Engine revision 0545f8705d
    • Dart version 3.1.5
    • DevTools version 2.25.0

[√] Windows Version (Installed version of Windows is version 10 or higher)

[!] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at C:\Users\pnv_fch\AppData\Local\Android\Sdk
    X cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    X Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Visual Studio - develop Windows apps (Visual Studio Enterprise 2022 17.6.5)
    • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Enterprise
    • Visual Studio Enterprise 2022 version 17.6.33829.357
    • Windows 10 SDK version 10.0.22000.0

[√] Android Studio (version 2022.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-b2043.56-10027231)

[√] Connected device (3 available)
    • SM A105FN (mobile) • R58N30FEYRV • android-arm    • Android 11 (API 30)
    • Windows (desktop)  • windows     • windows-x64    • Microsoft Windows [version 10.0.22621.2428]
    • Chrome (web)       • chrome      • web-javascript • Google Chrome 118.0.5993.89

[√] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

How to reproduce?

  • Take a picture with the phone's camera
  • Call the method getSize on the produced file

When i tried doing that, an exception was thrown by lib/src/image_size_getter.dart:123

   112    static Size getSize(ImageInput input) {
   113      if (!input.exists()) {
   114        throw StateError('The input is not exists.');
   115      }
   116
   117      for (var value in _decoders) {
   118        if (value.isValid(input)) {
   119          return value.getSize(input);
   120        }
   121      }
   122
   123      throw UnsupportedError('The input is not supported.');
   124    }

Of couse that means that the condition value.isValid(input) evaluated to false for decoders, but the specific problem here is that the isValid from the JPEG decoder returned false.

I looked into why the JPEG decoder doesn't recognise the file as proper JPEG, and found out that the file I tested with has a valid header, but the footer check failed.

I then inspected how the footer check was written, found out that you expect to find the two bytes 0xFF, 0xD9 at the very end of the file. On the file I tested with, the two last bytes are 0x46, 0x54 (ascii F, ascii T). So this is why the footer check failed.

But this file should be valid JPEG, since (firstly it ends with .jpg), my phone can render it, and Flutter's Image renders it well, too.

So I did some research, learnt the basics of JPEG markers, and that the 0xFF 0xD9 marker is not the "End of JPEG file" marker. It is the "End of Image" marker (EOI for short), meaning that a valid JPEG file can contain data after this EOI marker; thus it is not mandatory for a JPEG file to end with 0xFF 0xD9.

I then checked by hand, and the picture I tested with does contain this EOI marker, a few tens of bytes before the end of file.

Here is a link to the picture I tested with, if it helps you testing.

Logs

════════ Exception caught by widgets library ═══════════════════════════════════
The following UnsupportedError was thrown building KeyedSubtree-[GlobalKey#cc1b6]:
Unsupported operation: The input is not supported.

Failed to create image decoder with message 'unimplemented'

Version

2.1.2

Platforms

Android

Device Model

none

flutter info

Failed to create image decoder with message 'unimplemented'

How to reproduce?

final thumbPathFile = File(thumbPath);
final size = ImageSizeGetter.getSize(FileInput(thumbPathFile));
print('图片宽:${size.width}');
print('图片高:${size.height}');

Logs

Failed to create image decoder with message 'unimplemented'

Example code (optional)

final thumbPathFile = File(thumbPath);
final size = ImageSizeGetter.getSize(FileInput(thumbPathFile));
print('图片宽:${size.width}');
print('图片高:${size.height}');

Contact

[email protected]

Can't get size image

Hi @CaiJingLong @JiachenRen
I can;t get size image when use image_size_getter.
this is error when me get size .
The following FileSystemException was thrown attaching to the render tree:
Cannot retrieve length of file, path = 'assets/images/123.jpg'
this my code
final file = File('assets/images/123.jpg');
final size = ImageSizGetter.getSize(file);
Can you help me ?

[Feature request] Replace your `Size` with some child of ui.Size

Platforms

dart

Description

Now your Size interfere with dart:ui Size. It would be good to have your own class. For example:

class ImageSize extends Size {
  ...
}

Why

It will not confuses the user because Size is just a base object with width and height. You bring your own sense - it is image size (moreover with the additional boolean).

[Feature request] Return the image type

Platforms

dart

Description

In addition to returning a size, it would be useful to return the image type (PNG, JPG, etc).

The implementation of ImageSizeGetter.getSize seems to cycle though each image format, to check if it's a valid image, and then return the size for the first valid one. It would be useful to also return the image type, so this can be used by the caller.

Why

To validate the image is the expected file format, or to just determine the file format.

Allow network input

One of the most useful use cases for determining the image size without having to parse the entire image is when you load a big image over the network of unknown dimensions and want to determine the layout as early as possible.

The StreamedResponse of Dart's http library already provides a mechanism for accessing part of the data without having to wait for the entire response to be completed.

Unfortunately it is not possible to implement ImageInput on such a network image, because http works asynchronously.
It would be really great if you could make the getRange method async and better yet create a NetworkInput class

FileInput isn't defined

lib/crop_image.dart:35:46: Error: The method 'FileInput' isn't defined for the class '_CropImageState'.

  • '_CropImageState' is from 'package:course/crop_image.dart' ('lib/crop_image.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'FileInput'.
    imagePixelSize = ImageSizeGetter.getSize(FileInput(widget.file))

BMP support?

Hello,

It would be nice to have BMP support. It is the most basic type of image.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.