提交 53a1188e authored 作者: JarvanMo's avatar JarvanMo

thumbnail on android

上级 f84f12bc
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Flutter",
"request": "launch",
"type": "dart"
}
]
}
\ No newline at end of file
package com.jarvan.fluwx package com.jarvan.fluwx
import android.util.Log
import com.jarvan.fluwx.constant.CallResult import com.jarvan.fluwx.constant.CallResult
import com.jarvan.fluwx.constant.WeChatPluginMethods import com.jarvan.fluwx.constant.WeChatPluginMethods
import com.jarvan.fluwx.handler.WeChatPluginHandler import com.jarvan.fluwx.handler.WeChatPluginHandler
...@@ -22,6 +23,7 @@ class FluwxPlugin(private var registrar: Registrar) : MethodCallHandler { ...@@ -22,6 +23,7 @@ class FluwxPlugin(private var registrar: Registrar) : MethodCallHandler {
} }
override fun onMethodCall(call: MethodCall, result: Result): Unit { override fun onMethodCall(call: MethodCall, result: Result): Unit {
Log.e("---",call.method)
if(call.method == WeChatPluginMethods.INIT ){ if(call.method == WeChatPluginMethods.INIT ){
val api = WXAPIFactory.createWXAPI(registrar.context().applicationContext, call.arguments as String?) val api = WXAPIFactory.createWXAPI(registrar.context().applicationContext, call.arguments as String?)
api.registerApp(call.arguments as String) api.registerApp(call.arguments as String)
......
...@@ -50,11 +50,12 @@ object WeChatPluginHandler { ...@@ -50,11 +50,12 @@ object WeChatPluginHandler {
fun handle(call: MethodCall, result: MethodChannel.Result) { fun handle(call: MethodCall, result: MethodChannel.Result) {
Log.e("---",call.method)
if (!wxApi!!.isWXAppInstalled) { if (!wxApi!!.isWXAppInstalled) {
result.error(CallResult.RESULT_WE_CHAT_NOT_INSTALLED, CallResult.RESULT_WE_CHAT_NOT_INSTALLED, null) result.error(CallResult.RESULT_WE_CHAT_NOT_INSTALLED, CallResult.RESULT_WE_CHAT_NOT_INSTALLED, null)
return return
} }
when (call.method) { when (call.method) {
WeChatPluginMethods.SHARE_TEXT -> shareText(call, result) WeChatPluginMethods.SHARE_TEXT -> shareText(call, result)
WeChatPluginMethods.SHARE_MINI_PROGRAM -> shareMiniProgram(call, result) WeChatPluginMethods.SHARE_MINI_PROGRAM -> shareMiniProgram(call, result)
...@@ -151,11 +152,9 @@ object WeChatPluginHandler { ...@@ -151,11 +152,9 @@ object WeChatPluginHandler {
if (thumbnail.isNullOrBlank()){ if (thumbnail.isNullOrBlank()){
thumbnail = imagePath thumbnail = imagePath
} }
Log.e("tag","$thumbnail")
val thumbnailData = getThumbnailByteArrayCommon(registrar,thumbnail!!) val thumbnailData = getThumbnailByteArrayCommon(registrar,thumbnail!!)
// val thumbnailData = Util.bmpToByteArray(bitmap,true) // val thumbnailData = Util.bmpToByteArray(bitmap,true)
handleShareImage(imgObj,call,thumbnailData,result) handleShareImage(imgObj,call,thumbnailData,result)
} }
...@@ -197,17 +196,21 @@ object WeChatPluginHandler { ...@@ -197,17 +196,21 @@ object WeChatPluginHandler {
msg.title = call.argument("title") msg.title = call.argument("title")
msg.description = call.argument("description") msg.description = call.argument("description")
val thumbnail: String? = call.argument("thumbnail") val thumbnail: String? = call.argument("thumbnail")
launch(UI){
if (thumbnail != null && thumbnail.isNotBlank()) { if (thumbnail != null && thumbnail.isNotBlank()) {
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail, registrar) msg.thumbData = getThumbnailByteArrayCommon(registrar,thumbnail)
} }
val req = SendMessageToWX.Req() val req = SendMessageToWX.Req()
setCommonArguments(call, req, msg) setCommonArguments(call, req, msg)
req.message = msg req.message = msg
result.success(wxApi?.sendReq(req)) result.success(wxApi?.sendReq(req))
} }
}
private fun shareVideo(call: MethodCall, result: MethodChannel.Result) { private fun shareVideo(call: MethodCall, result: MethodChannel.Result) {
val video = WXVideoObject() val video = WXVideoObject()
val videoUrl: String? = call.argument("videoUrl") val videoUrl: String? = call.argument("videoUrl")
...@@ -222,11 +225,11 @@ object WeChatPluginHandler { ...@@ -222,11 +225,11 @@ object WeChatPluginHandler {
msg.title = call.argument(WechatPluginKeys.TITLE) msg.title = call.argument(WechatPluginKeys.TITLE)
msg.description = call.argument(WechatPluginKeys.DESCRIPTION) msg.description = call.argument(WechatPluginKeys.DESCRIPTION)
val thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL) val thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL)
launch(UI){
if (thumbnail != null && thumbnail.isNotBlank()) { if (thumbnail != null && thumbnail.isNotBlank()) {
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail, registrar) msg.thumbData = getThumbnailByteArrayCommon(registrar,thumbnail)
} }
val req = SendMessageToWX.Req() val req = SendMessageToWX.Req()
setCommonArguments(call, req, msg) setCommonArguments(call, req, msg)
req.message = msg req.message = msg
...@@ -234,24 +237,29 @@ object WeChatPluginHandler { ...@@ -234,24 +237,29 @@ object WeChatPluginHandler {
} }
}
private fun shareWebPage(call: MethodCall, result: MethodChannel.Result) { private fun shareWebPage(call: MethodCall, result: MethodChannel.Result) {
val webPage = WXWebpageObject() val webPage = WXWebpageObject()
webPage.webpageUrl = call.argument("webPage") webPage.webpageUrl = call.argument("webPage")
val msg = WXMediaMessage() val msg = WXMediaMessage()
Log.e("tag","share web")
msg.mediaObject = webPage msg.mediaObject = webPage
msg.title = call.argument(WechatPluginKeys.TITLE) msg.title = call.argument(WechatPluginKeys.TITLE)
msg.description = call.argument(WechatPluginKeys.DESCRIPTION) msg.description = call.argument(WechatPluginKeys.DESCRIPTION)
val thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL) val thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL)
launch(UI) {
if (thumbnail != null && thumbnail.isNotBlank()) { if (thumbnail != null && thumbnail.isNotBlank()) {
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail, registrar) msg.thumbData = getThumbnailByteArrayCommon(registrar, thumbnail)
} }
val req = SendMessageToWX.Req() val req = SendMessageToWX.Req()
setCommonArguments(call, req, msg) setCommonArguments(call, req, msg)
req.message = msg req.message = msg
result.success(wxApi?.sendReq(req)) result.success(wxApi?.sendReq(req))
} }
}
// private fun createWxImageObject(imagePath:String):WXImageObject?{ // private fun createWxImageObject(imagePath:String):WXImageObject?{
// var imgObj: WXImageObject? = null // var imgObj: WXImageObject? = null
......
...@@ -16,6 +16,8 @@ import junit.framework.Assert; ...@@ -16,6 +16,8 @@ import junit.framework.Assert;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log; import android.util.Log;
class Util { class Util {
...@@ -44,6 +46,41 @@ class Util { ...@@ -44,6 +46,41 @@ class Util {
} }
public static byte[] bmpToByteArray2(final Bitmap bmp, final boolean needRecycle) {
int i;
int j;
if (bmp.getHeight() > bmp.getWidth()) {
i = bmp.getWidth();
j = bmp.getWidth();
} else {
i = bmp.getHeight();
j = bmp.getHeight();
}
Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.ARGB_4444);
Canvas localCanvas = new Canvas(localBitmap);
while (true) {
localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
if (needRecycle)
bmp.recycle();
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
localByteArrayOutputStream);
localBitmap.recycle();
byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
try {
localByteArrayOutputStream.close();
return arrayOfByte;
} catch (Exception e) {
// F.out(e);
}
i = bmp.getHeight();
j = bmp.getHeight();
}
}
public static byte[] getHtmlByteArray(final String url) { public static byte[] getHtmlByteArray(final String url) {
URL htmlUrl = null; URL htmlUrl = null;
InputStream inStream = null; InputStream inStream = null;
......
...@@ -9,6 +9,8 @@ import android.util.Log; ...@@ -9,6 +9,8 @@ import android.util.Log;
import com.jarvan.fluwx.constant.WeChatPluginImageSchema; import com.jarvan.fluwx.constant.WeChatPluginImageSchema;
import com.jarvan.fluwx.constant.WechatPluginKeys; import com.jarvan.fluwx.constant.WechatPluginKeys;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
...@@ -24,13 +26,14 @@ import okhttp3.Request; ...@@ -24,13 +26,14 @@ import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import okhttp3.ResponseBody; import okhttp3.ResponseBody;
import okio.BufferedSink; import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio; import okio.Okio;
import okio.Source; import okio.Source;
import top.zibin.luban.Luban; import top.zibin.luban.Luban;
public class WeChatThumbnailUtil { public class WeChatThumbnailUtil {
public static final int SHARE_IMAGE_THUMB_LENGTH = 32; public static final int SHARE_IMAGE_THUMB_LENGTH = 32;
private static final int COMMON_THUMB_WIDTH = 150; private static final int COMMON_THUMB_WIDTH = 10;
private WeChatThumbnailUtil() { private WeChatThumbnailUtil() {
} }
...@@ -102,58 +105,78 @@ public class WeChatThumbnailUtil { ...@@ -102,58 +105,78 @@ public class WeChatThumbnailUtil {
int size = SHARE_IMAGE_THUMB_LENGTH * 1024; int size = SHARE_IMAGE_THUMB_LENGTH * 1024;
try { try {
File file1 = Luban File compressedFile = Luban
.with(registrar.context()) .with(registrar.context())
.ignoreBy(SHARE_IMAGE_THUMB_LENGTH)
.setTargetDir(registrar.context().getCacheDir().getAbsolutePath()) .setTargetDir(registrar.context().getCacheDir().getAbsolutePath())
.ignoreBy(32)
.get(file.getAbsolutePath()); .get(file.getAbsolutePath());
if(file.length() <= 32 * 1024){ if (compressedFile.length() < SHARE_IMAGE_THUMB_LENGTH * 1024) {
return Util.bmpToByteArray(BitmapFactory.decodeFile(file1.getAbsolutePath()), true); Source source = Okio.source(compressedFile);
}else { BufferedSource bufferedSource = Okio.buffer(source);
return continueCompress(file1); byte[] bytes = bufferedSource.readByteArray();
source.close();
bufferedSource.close();
return bytes;
}
byte[] result = createScaledBitmapWithRatio(compressedFile);
if (result.length < SHARE_IMAGE_THUMB_LENGTH * 1024) {
return result;
} }
return createScaledBitmap(compressedFile);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return new byte[]{}; return new byte[]{};
} }
private static byte[] continueCompress(File file){ private static byte[] createScaledBitmapWithRatio(File file) {
// Bitmap bitmap = ThumbnailCompressUtil.makeNormalBitmap(file.getAbsolutePath(), -1, 32 * 1024);
// if (bitmap.getByteCount() <= size) { Bitmap originBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
// return bmpToByteArray(bitmap,true); Bitmap result = ThumbnailCompressUtil.createScaledBitmapWithRatio(originBitmap, COMMON_THUMB_WIDTH, true);
// }
// String path = file.getAbsolutePath();
// String suffix = path.substring(path.lastIndexOf("."), path.length());
// byte[] result = Util.bmpToByteArray(bitmap, true); return bmpToByteArray(result, suffix, true);
// if (result.length <= size) {
// return result;
// }
//
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Bitmap bitmap2 = ThumbnailCompressUtil.createScaledBitmapWithRatio(bitmap, COMMON_THUMB_WIDTH, false);
Util.getHtmlByteArray()
if(bitmap2.getByteCount() <= 32 * 1024){
return bmpToByteArray(bitmap2,true);
} }
bitmap = ThumbnailCompressUtil.createScaledBitmap(bitmap,COMMON_THUMB_WIDTH,true); private static byte[] createScaledBitmap(File file) {
Bitmap originBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Bitmap result = ThumbnailCompressUtil.createScaledBitmap(originBitmap, COMMON_THUMB_WIDTH, true);
return bmpToByteArray(result, ".png", true);
}
return bmpToByteArray(bitmap,true); private static byte[] bmpToByteArray(Bitmap bitmap, String suffix, boolean recycle) {
// int bytes = bitmap.getByteCount();
// ByteBuffer buf = ByteBuffer.allocate(bytes);
// bitmap.copyPixelsToBuffer(buf);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap.CompressFormat format = Bitmap.CompressFormat.PNG;
if (suffix.toLowerCase().equals(".jpg") || suffix.toLowerCase().equals(".jpeg")) {
format = Bitmap.CompressFormat.JPEG;
} }
private static byte[] bmpToByteArray(Bitmap bitmap, boolean recycle) { bitmap.compress(format, 100, byteArrayOutputStream);
int bytes = bitmap.getByteCount(); InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ByteBuffer buf = ByteBuffer.allocate(bytes); byte[] result = null;
bitmap.copyPixelsToBuffer(buf);
if (recycle) { if (recycle) {
bitmap.recycle(); bitmap.recycle();
} }
Source source = Okio.source(inputStream);
return buf.array(); BufferedSource bufferedSource = Okio.buffer(source);
try {
result = bufferedSource.readByteArray();
source.close();
bufferedSource.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
} }
private static File fromAssetForCommon(String thumbnail, PluginRegistry.Registrar registrar) { private static File fromAssetForCommon(String thumbnail, PluginRegistry.Registrar registrar) {
...@@ -168,8 +191,6 @@ public class WeChatThumbnailUtil { ...@@ -168,8 +191,6 @@ public class WeChatThumbnailUtil {
BufferedSink sink = Okio.buffer(Okio.sink(outputStream)); BufferedSink sink = Okio.buffer(Okio.sink(outputStream));
Source source = Okio.source(fileDescriptor.createInputStream()); Source source = Okio.source(fileDescriptor.createInputStream());
sink.writeAll(source); sink.writeAll(source);
sink.flush();
source.close(); source.close();
sink.close(); sink.close();
} catch (IOException e) { } catch (IOException e) {
...@@ -199,11 +220,8 @@ public class WeChatThumbnailUtil { ...@@ -199,11 +220,8 @@ public class WeChatThumbnailUtil {
result = File.createTempFile(UUID.randomUUID().toString(), getSuffix(url)); result = File.createTempFile(UUID.randomUUID().toString(), getSuffix(url));
OutputStream outputStream = new FileOutputStream(result); OutputStream outputStream = new FileOutputStream(result);
BufferedSink sink = Okio.buffer(Okio.sink(outputStream)); BufferedSink sink = Okio.buffer(Okio.sink(outputStream));
Source source = Okio.source(responseBody.byteStream()); sink.writeAll(responseBody.source());
sink.writeAll(source);
sink.flush(); sink.flush();
source.close();
sink.close(); sink.close();
} }
...@@ -214,6 +232,25 @@ public class WeChatThumbnailUtil { ...@@ -214,6 +232,25 @@ public class WeChatThumbnailUtil {
return result; return result;
} }
private static File inputStreamToFile(InputStream inputStream,String suffix) {
File result = null;
try {
result = File.createTempFile(UUID.randomUUID().toString(), suffix);
OutputStream outputStream = new FileOutputStream(result);
BufferedSink sink = Okio.buffer(Okio.sink(outputStream));
Source source = Okio.source(inputStream);
sink.writeAll(source);
sink.flush();
sink.close();
source.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static String getSuffix(String path) { private static String getSuffix(String path) {
String suffix = ".jpg"; String suffix = ".jpg";
int index = path.lastIndexOf("."); int index = path.lastIndexOf(".");
......
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Flutter",
"request": "launch",
"type": "dart"
}
]
}
\ No newline at end of file
...@@ -12,7 +12,7 @@ class MyApp extends StatefulWidget { ...@@ -12,7 +12,7 @@ class MyApp extends StatefulWidget {
} }
class _MyAppState extends State<MyApp> { class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
@override @override
void initState() { void initState() {
...@@ -27,22 +27,7 @@ class _MyAppState extends State<MyApp> { ...@@ -27,22 +27,7 @@ class _MyAppState extends State<MyApp> {
// Platform messages are asynchronous, so we initialize in an async method. // Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async { Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
// platformVersion = await Fluwx.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
} }
@override @override
...@@ -58,14 +43,18 @@ class _MyAppState extends State<MyApp> { ...@@ -58,14 +43,18 @@ class _MyAppState extends State<MyApp> {
var fluwx = Fluwx(); var fluwx = Fluwx();
// thumbnail: 'http://b.hiphotos.baidu.com/image/h%3D300/sign=4bfc640817d5ad6eb5f962eab1c939a3/8718367adab44aedb794e128bf1c8701a08bfb20.jpg', // thumbnail: 'http://b.hiphotos.baidu.com/image/h%3D300/sign=4bfc640817d5ad6eb5f962eab1c939a3/8718367adab44aedb794e128bf1c8701a08bfb20.jpg',
fluwx.share( fluwx.share(
WeChatShareImageModel( WeChatShareWebPageModel(
image: 'http://a.hiphotos.baidu.com/image/h%3D300/sign=91a426229082d158a4825fb1b00819d5/0824ab18972bd4077557733177899e510eb3096d.jpg', webPage: "https://www.jianshu.com/",
thumbnail:'http://a.hiphotos.baidu.com/image/h%3D300/sign=91a426229082d158a4825fb1b00819d5/0824ab18972bd4077557733177899e510eb3096d.jpg', title: "简书",
transaction:
'http://b.hiphotos.baidu.com/image/h%3D300/sign=4bfc640817d5ad6eb5f962eab1c939a3/8718367adab44aedb794e128bf1c8701a08bfb20.jpg', )
scene: WeChatScene.SESSION)); ).then((result){
print("--$result");
},onError: (msg){
print(msg);
});
}, },
child: new Text("share text to wechat")), child: new Text("share ")),
), ),
), ),
); );
......
...@@ -33,6 +33,7 @@ class Fluwx { ...@@ -33,6 +33,7 @@ class Fluwx {
} }
Future share(WeChatShareModel model) async { Future share(WeChatShareModel model) async {
var s = _shareModelMethodMapper[model.runtimeType];
if (_shareModelMethodMapper.containsKey(model.runtimeType)) { if (_shareModelMethodMapper.containsKey(model.runtimeType)) {
return await _channel.invokeMethod( return await _channel.invokeMethod(
_shareModelMethodMapper[model.runtimeType], model.toMap()); _shareModelMethodMapper[model.runtimeType], model.toMap());
......
...@@ -176,6 +176,7 @@ class WeChatShareMusicModel extends WeChatShareModel { ...@@ -176,6 +176,7 @@ class WeChatShareMusicModel extends WeChatShareModel {
this.title: "", this.title: "",
this.description: "", this.description: "",
this.musicDataUrl, this.musicDataUrl,
this.musicLowBandDataUrl,
String thumbnail, String thumbnail,
WeChatScene scene, WeChatScene scene,
String messageExt, String messageExt,
...@@ -269,7 +270,7 @@ class WeChatShareWebPageModel extends WeChatShareModel { ...@@ -269,7 +270,7 @@ class WeChatShareWebPageModel extends WeChatShareModel {
WeChatShareWebPageModel({ WeChatShareWebPageModel({
String transaction, String transaction,
this.webPage, @required this.webPage,
this.title: "", this.title: "",
this.description: "", this.description: "",
String thumbnail, String thumbnail,
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论