From 0cfac2b7090ef8adf7599d12340356a7190a0cba Mon Sep 17 00:00:00 2001 From: donguseo Date: Sun, 2 Aug 2020 21:34:42 +0900 Subject: [PATCH] add jpgPath param and use thread for android --- .packages | 2 +- CHANGELOG.md | 1 + README.md | 2 +- .../seo/dongu/heic_to_jpg/HeicToJpeg.kt | 7 +- .../seo/dongu/heic_to_jpg/HeicToJpgPlugin.kt | 84 +++++++++++-------- example/lib/main.dart | 61 ++++++++------ example/pubspec.lock | 9 +- example/pubspec.yaml | 3 + ios/Classes/SwiftHeicToJpgPlugin.swift | 12 ++- lib/heic_to_jpg.dart | 10 ++- pubspec.yaml | 3 +- 11 files changed, 116 insertions(+), 78 deletions(-) diff --git a/.packages b/.packages index 2455c5e..4d21b2e 100644 --- a/.packages +++ b/.packages @@ -1,4 +1,4 @@ -# Generated by pub on 2020-05-21 08:17:37.491594. +# Generated by pub on 2020-08-02 21:31:59.474280. archive:file:///Users/donguseo/development/flutter/.pub-cache/hosted/pub.dartlang.org/archive-2.0.11/lib/ args:file:///Users/donguseo/development/flutter/.pub-cache/hosted/pub.dartlang.org/args-1.5.2/lib/ async:file:///Users/donguseo/development/flutter/.pub-cache/hosted/pub.dartlang.org/async-2.4.0/lib/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 9eb8a36..9dde505 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ ## [0.0.1] initial commit ## [0.1.0] publish at pub.dev ## [0.1.1] remove test because of error +## [0.1.1] add jpgPath param and use thread for android \ No newline at end of file diff --git a/README.md b/README.md index c8072e7..1a1ff5f 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ With this plugin you can convert HEIC/HEIF file to JPEG image easily Add the Package ```yaml dependencies: - heic_to_jpg: ^0.1.1 + heic_to_jpg: ^0.1.2 ``` ## How to use diff --git a/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpeg.kt b/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpeg.kt index 809edc5..39b9213 100644 --- a/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpeg.kt +++ b/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpeg.kt @@ -6,13 +6,10 @@ import java.io.File import java.io.FileOutputStream import java.lang.Exception -fun convertHeicToJpeg(heic: String, cacheDir: File?) : String? { - if(cacheDir == null){ - return null - } +fun convertHeicToJpeg(heic: String, outputFile: String) : String? { try { val bitmap = BitmapFactory.decodeFile(heic) - val file = File(cacheDir.path + "/${System.currentTimeMillis()}.jpg") + val file = File(outputFile) file.createNewFile() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(file)); return file.path diff --git a/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpgPlugin.kt b/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpgPlugin.kt index 69e4010..56f3bf7 100644 --- a/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpgPlugin.kt +++ b/android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpgPlugin.kt @@ -1,6 +1,8 @@ package seo.dongu.heic_to_jpg import android.content.Context +import android.os.Handler +import android.os.Looper import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall @@ -10,44 +12,58 @@ import io.flutter.plugin.common.MethodChannel.Result import io.flutter.plugin.common.PluginRegistry.Registrar /** HeicToJpgPlugin */ -class HeicToJpgPlugin: FlutterPlugin, MethodCallHandler { +class HeicToJpgPlugin : FlutterPlugin, MethodCallHandler { - override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { - applicationContext = flutterPluginBinding.applicationContext - val channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "heic_to_jpg") - channel.setMethodCallHandler(HeicToJpgPlugin()); - } + override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + applicationContext = flutterPluginBinding.applicationContext + val channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "heic_to_jpg") + channel.setMethodCallHandler(HeicToJpgPlugin()); + } - // This static function is optional and equivalent to onAttachedToEngine. It supports the old - // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting - // plugin registration via this function while apps migrate to use the new Android APIs - // post-flutter-1.12 via https://flutter.dev/go/android-project-migration. - // - // It is encouraged to share logic between onAttachedToEngine and registerWith to keep - // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called - // depending on the user's project. onAttachedToEngine or registerWith must both be defined - // in the same class. - companion object { - var applicationContext :Context? = null - @JvmStatic - fun registerWith(registrar: Registrar) { - val channel = MethodChannel(registrar.messenger(), "heic_to_jpg") - channel.setMethodCallHandler(HeicToJpgPlugin()) + // This static function is optional and equivalent to onAttachedToEngine. It supports the old + // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting + // plugin registration via this function while apps migrate to use the new Android APIs + // post-flutter-1.12 via https://flutter.dev/go/android-project-migration. + // + // It is encouraged to share logic between onAttachedToEngine and registerWith to keep + // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called + // depending on the user's project. onAttachedToEngine or registerWith must both be defined + // in the same class. + companion object { + var applicationContext: Context? = null + @JvmStatic + fun registerWith(registrar: Registrar) { + val channel = MethodChannel(registrar.messenger(), "heic_to_jpg") + channel.setMethodCallHandler(HeicToJpgPlugin()) + } } - } - override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { - if (call.method == "convert") { - if(call.hasArgument("heicPath") && !call.argument("heicPath").isNullOrEmpty()){ - result.success(convertHeicToJpeg(call.argument("heicPath")!!, applicationContext?.cacheDir)) - return - } - result.error("illegalArgument", "heicPath is null or Empty.", null) - } else { - result.notImplemented() + override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { + if (call.method == "convert") { + if (call.hasArgument("heicPath") && !call.argument("heicPath").isNullOrEmpty()) { + val handler = Handler(Looper.getMainLooper()) + Thread { + var jpgPath = call.argument("jpgPath") + if(jpgPath.isNullOrEmpty()){ + jpgPath = "${applicationContext?.cacheDir}/${System.currentTimeMillis()}.jpg" + } + val output = convertHeicToJpeg(call.argument("heicPath")!!, jpgPath) + handler.post { + if (output != null) { + result.success(output) + } else { + result.error("error", "output path is null", null) + } + } + }.start() + return + } + result.error("illegalArgument", "heicPath is null or Empty.", null) + } else { + result.notImplemented() + } } - } - override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { - } + override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { + } } diff --git a/example/lib/main.dart b/example/lib/main.dart index d906c37..6dbec5d 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -6,8 +6,9 @@ import 'dart:async'; import 'package:heic_to_jpg/heic_to_jpg.dart'; import 'package:path_provider/path_provider.dart'; +import 'package:future_progress_dialog/future_progress_dialog.dart'; -void main() => runApp(MyApp()); +void main() => runApp(MaterialApp(home: MyApp())); class MyApp extends StatefulWidget { @override @@ -17,43 +18,49 @@ class MyApp extends StatefulWidget { class _MyAppState extends State { String heicUrl = 'https://filesamples.com/samples/image/heic/sample1.heic'; String jpeg; - @override - void initState() { - super.initState(); - initPlatformState(); - } + bool initialized = false; // Platform messages are asynchronous, so we initialize in an async method. Future initPlatformState() async { - File heicFile = await _downloadFile(heicUrl, 'a.heic'); - String tmp = await HeicToJpg.convert(heicFile.path); - setState(() { - jpeg = tmp; + if (initialized) return; + initialized = true; + WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) async { + String tmp = await showDialog( + context: context, child: FutureProgressDialog(downloadAndConvert())); + setState(() { + jpeg = tmp; + }); }); } + Future downloadAndConvert() async { + File heicFile = await _downloadFile(heicUrl, 'a.heic'); + return HeicToJpg.convert(heicFile.path); + } + @override Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), - body: Center( - child: (jpeg != null && jpeg.isNotEmpty)? Image.file(File(jpeg)) : Text('No Image'), - ), + initPlatformState(); + return Scaffold( + appBar: AppBar( + title: const Text('Plugin example app'), + ), + body: Center( + child: (jpeg != null && jpeg.isNotEmpty) + ? Image.file(File(jpeg)) + : Text('No Image'), ), ); } static var httpClient = new HttpClient(); -Future _downloadFile(String url, String filename) async { - var request = await httpClient.getUrl(Uri.parse(url)); - var response = await request.close(); - var bytes = await consolidateHttpClientResponseBytes(response); - String dir = (await getTemporaryDirectory()).path; - File file = new File('$dir/$filename'); - await file.writeAsBytes(bytes); - return file; -} + Future _downloadFile(String url, String filename) async { + var request = await httpClient.getUrl(Uri.parse(url)); + var response = await request.close(); + var bytes = await consolidateHttpClientResponseBytes(response); + String dir = (await getTemporaryDirectory()).path; + File file = new File('$dir/$filename'); + await file.writeAsBytes(bytes); + return file; + } } diff --git a/example/pubspec.lock b/example/pubspec.lock index 57051e9..9423342 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -74,13 +74,20 @@ packages: description: flutter source: sdk version: "0.0.0" + future_progress_dialog: + dependency: "direct dev" + description: + name: future_progress_dialog + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.1" heic_to_jpg: dependency: "direct dev" description: path: ".." relative: true source: path - version: "0.1.1" + version: "0.1.2" image: dependency: transitive description: diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 2d2c647..a32e9eb 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -2,6 +2,7 @@ name: heic_to_jpg_example description: Demonstrates how to use the heic_to_jpg plugin. publish_to: 'none' + environment: sdk: ">=2.1.0 <3.0.0" @@ -21,6 +22,8 @@ dev_dependencies: heic_to_jpg: path: ../ + future_progress_dialog: ^0.1.1 + # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/ios/Classes/SwiftHeicToJpgPlugin.swift b/ios/Classes/SwiftHeicToJpgPlugin.swift index e4f7d62..1acac4d 100644 --- a/ios/Classes/SwiftHeicToJpgPlugin.swift +++ b/ios/Classes/SwiftHeicToJpgPlugin.swift @@ -10,10 +10,16 @@ public class SwiftHeicToJpgPlugin: NSObject, FlutterPlugin { public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if(call.method == "convert"){ - let dic = call.arguments as! NSDictionary + let dic = call.arguments as! Dictionary let heicPath = dic["heicPath"] as! String - let jpegPath = NSTemporaryDirectory().appendingFormat("%d.jpg", Date().timeIntervalSince1970 * 1000) - result(fromHeicToJpg(heicPath: heicPath, jpgPath: jpegPath)) + var jpgPath :String? + if(!(dic["jpgPath"] is NSNull)){ + jpgPath = dic["jpgPath"] as! String? + } + if(jpgPath == nil || jpgPath!.isEmpty){ + jpgPath = NSTemporaryDirectory().appendingFormat("%d.jpg", Date().timeIntervalSince1970 * 1000) + } + result(fromHeicToJpg(heicPath: heicPath, jpgPath: jpgPath!)) } } diff --git a/lib/heic_to_jpg.dart b/lib/heic_to_jpg.dart index f566dd5..e2d4424 100644 --- a/lib/heic_to_jpg.dart +++ b/lib/heic_to_jpg.dart @@ -6,10 +6,12 @@ class HeicToJpg { static const MethodChannel _channel = const MethodChannel('heic_to_jpg'); /// Convert HEIC/HEIF Image to JPEG Image. - /// Get [heic] path as an input and return [jpg] path. - static Future convert(String heic) async { - final String jpg = - await _channel.invokeMethod('convert', {"heicPath": heic}); + /// Get [heicPath] path as an input and return [jpg] path. + /// You can set [jpgPath] if you want to set the output file path. + /// If you don't set it the output file path is made in cache directory of each platform. + static Future convert(String heicPath, {String jpgPath}) async { + final String jpg = await _channel + .invokeMethod('convert', {"heicPath": heicPath, "jpgPath": jpgPath}); return jpg; } } diff --git a/pubspec.yaml b/pubspec.yaml index de2f43b..55d609f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,6 @@ name: heic_to_jpg description: With this library you can convert HEIC/HEIF file to JPEG image easily -version: 0.1.1 -author: donguseo +version: 0.1.2 homepage: https://github.com/donguseo/flutter_heic_to_jpg environment: