Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is their any way to convert .jpeg images to .gif?

Is there anyway to convert images to a video? (It doesn't have to be .gif necessarily)

To be more specific, I am using Google Firebase as my storage cloud server to upload pictures taken by camera plugin of Flutter.

I want to convert my images to a video so that it looks like a time-lapse video.


The pictures are taken by camera plugin which uses camera.dart, and it is stored it Firebase storage like this:

onCapture(context) async {
try {
  final p = await getTemporaryDirectory();
  var now = DateTime.now();
  var formattedDate = DateFormat('yy-MM-dd HH:mm:ss').format(now);
  final path = '${p.path}/$now.png';
  await cameraController.takePicture(path).then((value) {
    print('here');
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => PreviewScreen(
                  imgPath: path,
                  fileName: '$formattedDate.png',
                  pickedTime: '$formattedDate',
                )));
  });
} catch (e) {
  showCameraException(e);
 }
}

edit : Before constructing gif, i am having trouble downloading an image from firebase and putting this image on the canvas. I think I can use your code to make a gif once I do this.

import 'dart:io';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:image/image.dart' as IMG;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:firebase_core/firebase_core.dart' as firebase_core;
import 'package:provider/provider.dart';
import 'package:weighit/models/user_info.dart';

class ToGif extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Timelapse Video'),
      ),
      body: Container(
        child: Thumbnail(),
      ),
    );
  }
}

class Thumbnail extends StatefulWidget {
  const Thumbnail({Key key}) : super(key: key);
  @override
  _ThumbnailState createState() => _ThumbnailState();
}

class _ThumbnailState extends State<Thumbnail> {
  List<int> imgBytes;
  Isolate isolate;
  File image;

  @override
  void initState() {
    _asyncInit();

    super.initState();
  }

  static _isolateEntry(dynamic d) async {
    final ReceivePort receivePort = ReceivePort();
    d.send(receivePort.sendPort);

    final config = await receivePort.first;

    print(config);

    final file = File(config['path']);
    final bytes = await file.readAsBytes();

    IMG.Image image = IMG.decodeImage(bytes);
    IMG.Image thumbnail = IMG.copyResize(
      image,
      width: config['size'].width.toInt(),
    );

    d.send(IMG.encodeNamedImage(thumbnail, basename(config['path'])));
  }

  _asyncInit() async {
    final receivePort = ReceivePort();
    isolate = await Isolate.spawn(_isolateEntry, receivePort.sendPort);

    receivePort.listen((dynamic data) {
      if (data is SendPort) {
        if (mounted) {
          data.send({
            'path': image.path,
            'size': Size(500, 500),
          });
        }
      } else {
        if (mounted) {
          setState(() {
            imgBytes = data;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    if (isolate != null) {
      isolate.kill();
    }
    super.dispose();
  }

  // Download on DocumnetDirectory, not temporary directory https://flutter-ko.dev/docs/cookbook/persistence/reading-writing-files
  Future<void> downloadFileExample() async {
    final appDocDir = await getApplicationDocumentsDirectory();
    image = File('${appDocDir.path}/download-logo.png');

    try {
      await firebase_storage.FirebaseStorage.instance
          // can not find proper reference path...
          .ref('gs://weighit-f506b.appspot.com/guny/21-04-26 10:56:21.png')
          .writeToFile(image);
    } on firebase_core.FirebaseException catch (e) {
      print('couldnt find the reference');
    }
  }

  @override
  Widget build(BuildContext context) {
    final _user = Provider.of<TheUser>(context);
    return FutureBuilder(
      future: downloadFileExample(),
      builder: (context, snapshot) {
        //해당 부분은 data를 아직 받아 오지 못했을때 실행되는 부분을 의미한다.
        if (snapshot.hasData == false) {
          return Center(child: CircularProgressIndicator());
        }
        //error가 발생하게 될 경우 반환하게 되는 부분
        else if (snapshot.hasError) {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(
              'Error: ${snapshot.error}',
              style: TextStyle(fontSize: 15),
            ),
          );
        } else {
          return SizedBox(
            height: 500,
            width: 500,
            child: imgBytes != null
                ? Image.memory(
                    imgBytes,
                    fit: BoxFit.cover,
                  )
                : Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Colors.grey[100], Colors.grey[300]],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                      ),
                    ),
                  ),
          );
        }
      },
    );
  }
}
like image 688
John Park Avatar asked Oct 19 '25 15:10

John Park


1 Answers

You can use the image package to created animated GIFs from multiple images.

First add it as a dependency:

dependencies:
  image: ^3.0.2

Then to you can make a function to generate an animated GIF from multiple images:

List<int>? generateGIF(Iterable<Image> images) {
  final Animation animation = Animation();
  for(Image image in images) {
    animation.addFrame(image);
  }
  return encodeGifAnimation(animation);
}

To use this function with multiple images that are in files from the camera package in the form of XFiles, you have to decode the images for each of those files and pass it to this function. The following code assumes you know that these are JPEG images:

List<XFile> imageFiles = ...;

final JpegDecoder decoder = JpegDecoder();
final List<Image> images = [];
for(var imgFile in imageFiles) {
  Uint8List data = await imgFile.readAsBytes();
  images.add(decoder.decodeImage(data));
}

List<int>? gifData = generateGIF(images);
like image 131
Christopher Moore Avatar answered Oct 21 '25 06:10

Christopher Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!