Skip to content
This repository has been archived by the owner on Dec 2, 2022. It is now read-only.

Commit

Permalink
add jpgPath param and use thread for android
Browse files Browse the repository at this point in the history
  • Loading branch information
donguseo committed Aug 2, 2020
1 parent 1c5293e commit 0cfac2b
Show file tree
Hide file tree
Showing 11 changed files with 116 additions and 78 deletions.
2 changes: 1 addition & 1 deletion .packages
Original file line number Diff line number Diff line change
@@ -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/
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 2 additions & 5 deletions android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpeg.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
84 changes: 50 additions & 34 deletions android/src/main/kotlin/seo/dongu/heic_to_jpg/HeicToJpgPlugin.kt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<String>("heicPath").isNullOrEmpty()){
result.success(convertHeicToJpeg(call.argument<String>("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<String>("heicPath").isNullOrEmpty()) {
val handler = Handler(Looper.getMainLooper())
Thread {
var jpgPath = call.argument<String>("jpgPath")
if(jpgPath.isNullOrEmpty()){
jpgPath = "${applicationContext?.cacheDir}/${System.currentTimeMillis()}.jpg"
}
val output = convertHeicToJpeg(call.argument<String>("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) {
}
}
61 changes: 34 additions & 27 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -17,43 +18,49 @@ class MyApp extends StatefulWidget {
class _MyAppState extends State<MyApp> {
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<void> 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<String> 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<File> _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<File> _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;
}
}
9 changes: 8 additions & 1 deletion example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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

Expand Down
12 changes: 9 additions & 3 deletions ios/Classes/SwiftHeicToJpgPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Any>
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!))
}
}

Expand Down
10 changes: 6 additions & 4 deletions lib/heic_to_jpg.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> 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<String> convert(String heicPath, {String jpgPath}) async {
final String jpg = await _channel
.invokeMethod('convert', {"heicPath": heicPath, "jpgPath": jpgPath});
return jpg;
}
}
3 changes: 1 addition & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -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<[email protected]>
version: 0.1.2
homepage: https://github.com/donguseo/flutter_heic_to_jpg

environment:
Expand Down

0 comments on commit 0cfac2b

Please sign in to comment.