How to convert image stream buffer into jpeg image bytes in flutter for iOS?

6,420

Take a look at the pub.dev image library API at https://pub.dev/packages/image. It converts from any image format, regardless of it being bgra8888 or yuv420. This example converts it to a PNG file:

import 'dart:io';
import 'package:image/image.dart';
void main() {
  // Read an image from file
  // decodeImage will identify the format of the image and use the appropriate
  // decoder.
  Image image = decodeImage(File('test.bgra8888').readAsBytesSync());

  // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
  Image thumbnail = copyResize(image, width: 120);

  // Save the thumbnail as a PNG.
  File('thumbnail.png').writeAsBytesSync(encodePng(thumbnail));
}
Share:
6,420
Almas Adilbek
Author by

Almas Adilbek

Geek designer. I'm focused on quality products, where every single pixel is indispensable., Founder of Sajda.mobi & Kaz.News

Updated on December 13, 2022

Comments

  • Almas Adilbek
    Almas Adilbek over 1 year

    When we deal with camera in flutter, we use Camera plugin.
    It has .startImageStream method which returns CameraImage cameraImage data type.

    In iOS, cameraImage.format is bgra8888.
    For android cameraImage.format is yuv420.

    Before encoding these formats to JPEG or PNG, we need some bytes manipulation and put each byte into image buffer, which is then used in JpegEncoder.

    For android, cameraImage(yuv420) to List<int> is discussed and implemented in this issue: https://github.com/flutter/flutter/issues/26348#issuecomment-462321428

    The question is, how do we construct flutter Image(jpeg|png) from bgra8888 cameraImage?

  • Kohls
    Kohls over 4 years
    Op requested conversion to JPG, not PNG
  • Kamlesh
    Kamlesh over 3 years
    any solution for jpg image??
  • rexxar
    rexxar about 3 years
    the solution for JPG is to rename the file to thumbnail.jpg and use the encodeJpg method instead of encodePng
  • Taufik Nur Rahmanda
    Taufik Nur Rahmanda about 2 years
    then how to set jpg background to white?