提交 30186a5e authored 作者: JarvanMo's avatar JarvanMo

share thumbnails ok

上级 b7fbd402
...@@ -50,7 +50,6 @@ object WeChatPluginHandler { ...@@ -50,7 +50,6 @@ 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
...@@ -98,23 +97,32 @@ object WeChatPluginHandler { ...@@ -98,23 +97,32 @@ object WeChatPluginHandler {
val msg = WXMediaMessage(miniProgramObj) val msg = WXMediaMessage(miniProgramObj)
msg.title = call.argument("title") // 小程序消息title msg.title = call.argument("title") // 小程序消息title
msg.description = call.argument("description") // 小程序消息desc msg.description = call.argument("description") // 小程序消息desc
var thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL) val thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL)
thumbnail = thumbnail ?: ""
if (thumbnail.isNullOrBlank()) {
msg.thumbData = null
} else {
msg.thumbData = WeChatThumbnailUtil.thumbnailForMiniProgram(thumbnail, registrar)
}
launch {
if (thumbnail.isNullOrBlank()) {
msg.thumbData = null
} else {
msg.thumbData = getThumbnailByteArrayMiniProgram(registrar,thumbnail!!)
}
val req = SendMessageToWX.Req()
setCommonArguments(call, req, msg)
req.message = msg
result.success(wxApi?.sendReq(req))
}
val req = SendMessageToWX.Req()
setCommonArguments(call, req, msg)
req.message = msg
result.success(wxApi?.sendReq(req))
} }
private suspend fun getThumbnailByteArrayMiniProgram(registrar: PluginRegistry.Registrar?,thumbnail:String):ByteArray{
return async(CommonPool) {
val result = WeChatThumbnailUtil.thumbnailForMiniProgram(thumbnail, registrar)
result?: byteArrayOf()
}.await()
}
private suspend fun getImageByteArrayCommon(registrar: PluginRegistry.Registrar?,imagePath:String):ByteArray{ private suspend fun getImageByteArrayCommon(registrar: PluginRegistry.Registrar?,imagePath:String):ByteArray{
return async(CommonPool){ return async(CommonPool){
......
...@@ -3,7 +3,6 @@ package com.jarvan.fluwx.utils; ...@@ -3,7 +3,6 @@ package com.jarvan.fluwx.utils;
import android.content.res.AssetFileDescriptor; import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.util.Log;
import com.jarvan.fluwx.constant.WeChatPluginImageSchema; import com.jarvan.fluwx.constant.WeChatPluginImageSchema;
...@@ -12,12 +11,10 @@ import com.jarvan.fluwx.constant.WechatPluginKeys; ...@@ -12,12 +11,10 @@ import com.jarvan.fluwx.constant.WechatPluginKeys;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.UUID; import java.util.UUID;
import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugin.common.PluginRegistry;
...@@ -32,85 +29,64 @@ import okio.Source; ...@@ -32,85 +29,64 @@ import okio.Source;
import top.zibin.luban.Luban; import top.zibin.luban.Luban;
public class WeChatThumbnailUtil { public class WeChatThumbnailUtil {
public static final int SHARE_MINI_PROGRAM_IMAGE_THUMB_LENGTH = 120;
public static final int MINI_PROGRAM_SCALED_WIDTH = 480;
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 = 10; private static final int COMMON_THUMB_WIDTH = 150;
private WeChatThumbnailUtil() { private WeChatThumbnailUtil() {
} }
public static byte[] thumbnailForMiniProgram(String thumbnail, PluginRegistry.Registrar registrar) { public static byte[] thumbnailForMiniProgram(String thumbnail, PluginRegistry.Registrar registrar) {
byte[] result = null; File file;
if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_ASSETS)) { if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_ASSETS)) {
result = fromAssetForMiniProgram(thumbnail, registrar); file = getAssetFile(thumbnail, registrar);
} else if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_FILE)) { } else if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_FILE)) {
file = new File(thumbnail);
} else { } else {
file = downloadImage(thumbnail);
} }
return result; return compress(file, registrar,SHARE_MINI_PROGRAM_IMAGE_THUMB_LENGTH,MINI_PROGRAM_SCALED_WIDTH);
} }
private static byte[] fromAssetForMiniProgram(String thumbnail, PluginRegistry.Registrar registrar) { private static byte[] fromAssetForMiniProgram(String thumbnail, PluginRegistry.Registrar registrar) {
byte[] result = null; File file;
String key = thumbnail.substring(WeChatPluginImageSchema.SCHEMA_ASSETS.length(), thumbnail.length()); if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_ASSETS)) {
AssetFileDescriptor fileDescriptor = AssetManagerUtil.openAsset(registrar, key, getPackage(key)); file = getAssetFile(thumbnail, registrar);
} else if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_FILE)) {
if (fileDescriptor != null && fileDescriptor.getLength() <= 128 * 1024) { file = new File(thumbnail);
try { } else {
Source source = Okio.source(fileDescriptor.createInputStream()); file = downloadImage(thumbnail);
result = Okio.buffer(source).readByteArray();
source.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (fileDescriptor != null && fileDescriptor.getLength() > 128 * 1024) {
File file = FileUtil.createTmpFile(fileDescriptor);
if (file == null) {
return null;
}
File snapshot = CompressImageUtil.compressUtilSmallerThan(128, file, registrar.context());
if (snapshot == null) {
return null;
}
try {
result = Okio.buffer(Okio.source(snapshot)).readByteArray();
} catch (IOException e) {
e.printStackTrace();
}
} }
return compress(file, registrar,SHARE_MINI_PROGRAM_IMAGE_THUMB_LENGTH,MINI_PROGRAM_SCALED_WIDTH);
return result;
} }
public static byte[] thumbnailForCommon(String thumbnail, PluginRegistry.Registrar registrar) { public static byte[] thumbnailForCommon(String thumbnail, PluginRegistry.Registrar registrar) {
File file; File file;
if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_ASSETS)) { if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_ASSETS)) {
file = fromAssetForCommon(thumbnail, registrar); file = getAssetFile(thumbnail, registrar);
} else if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_FILE)) { } else if (thumbnail.startsWith(WeChatPluginImageSchema.SCHEMA_FILE)) {
file = new File(thumbnail); file = new File(thumbnail);
} else { } else {
file = downloadImage(thumbnail); file = downloadImage(thumbnail);
} }
return compress(file, registrar); return compress(file, registrar,SHARE_IMAGE_THUMB_LENGTH,COMMON_THUMB_WIDTH);
} }
private static byte[] compress(File file, PluginRegistry.Registrar registrar) { private static byte[] compress(File file, PluginRegistry.Registrar registrar,int resultMaxLength,int scaledWidth) {
if (file == null) { if (file == null) {
return new byte[]{}; return new byte[]{};
} }
int size = SHARE_IMAGE_THUMB_LENGTH * 1024;
try { try {
File compressedFile = Luban File compressedFile = Luban
.with(registrar.context()) .with(registrar.context())
.ignoreBy(SHARE_IMAGE_THUMB_LENGTH) .ignoreBy(resultMaxLength)
.setTargetDir(registrar.context().getCacheDir().getAbsolutePath()) .setTargetDir(registrar.context().getCacheDir().getAbsolutePath())
.get(file.getAbsolutePath()); .get(file.getAbsolutePath());
if (compressedFile.length() < SHARE_IMAGE_THUMB_LENGTH * 1024) { if (compressedFile.length() < resultMaxLength * 1024) {
Source source = Okio.source(compressedFile); Source source = Okio.source(compressedFile);
BufferedSource bufferedSource = Okio.buffer(source); BufferedSource bufferedSource = Okio.buffer(source);
byte[] bytes = bufferedSource.readByteArray(); byte[] bytes = bufferedSource.readByteArray();
...@@ -118,12 +94,12 @@ public class WeChatThumbnailUtil { ...@@ -118,12 +94,12 @@ public class WeChatThumbnailUtil {
bufferedSource.close(); bufferedSource.close();
return bytes; return bytes;
} }
byte[] result = createScaledBitmapWithRatio(compressedFile); byte[] result = createScaledBitmapWithRatio(compressedFile,scaledWidth);
if (result.length < SHARE_IMAGE_THUMB_LENGTH * 1024) { if (result.length < resultMaxLength * 1024) {
return result; return result;
} }
return createScaledBitmap(compressedFile); return createScaledBitmap(compressedFile, resultMaxLength,scaledWidth);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -131,10 +107,10 @@ public class WeChatThumbnailUtil { ...@@ -131,10 +107,10 @@ public class WeChatThumbnailUtil {
return new byte[]{}; return new byte[]{};
} }
private static byte[] createScaledBitmapWithRatio(File file) { private static byte[] createScaledBitmapWithRatio(File file,int scaledWidth) {
Bitmap originBitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); Bitmap originBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Bitmap result = ThumbnailCompressUtil.createScaledBitmapWithRatio(originBitmap, COMMON_THUMB_WIDTH, true); Bitmap result = ThumbnailCompressUtil.createScaledBitmapWithRatio(originBitmap, scaledWidth, true);
String path = file.getAbsolutePath(); String path = file.getAbsolutePath();
String suffix = path.substring(path.lastIndexOf("."), path.length()); String suffix = path.substring(path.lastIndexOf("."), path.length());
...@@ -143,9 +119,22 @@ public class WeChatThumbnailUtil { ...@@ -143,9 +119,22 @@ public class WeChatThumbnailUtil {
} }
private static byte[] createScaledBitmap(File file) { private static byte[] createScaledBitmap(File file,int resultMaxLength,int scaledWidth) {
Bitmap originBitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); Bitmap originBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Bitmap result = ThumbnailCompressUtil.createScaledBitmap(originBitmap, COMMON_THUMB_WIDTH, true);
Bitmap result = null;
int width =scaledWidth;
while (width > 10){
result = ThumbnailCompressUtil.createScaledBitmap(originBitmap, width, false);
if (result.getByteCount() < resultMaxLength* 1024){
break;
}else {
width = width -10;
}
}
originBitmap.recycle();
return bmpToByteArray(result, ".png", true); return bmpToByteArray(result, ".png", true);
} }
...@@ -179,7 +168,7 @@ public class WeChatThumbnailUtil { ...@@ -179,7 +168,7 @@ public class WeChatThumbnailUtil {
return result; return result;
} }
private static File fromAssetForCommon(String thumbnail, PluginRegistry.Registrar registrar) { private static File getAssetFile(String thumbnail, PluginRegistry.Registrar registrar) {
File result = null; File result = null;
String key = thumbnail.substring(WeChatPluginImageSchema.SCHEMA_ASSETS.length(), thumbnail.length()); String key = thumbnail.substring(WeChatPluginImageSchema.SCHEMA_ASSETS.length(), thumbnail.length());
AssetFileDescriptor fileDescriptor = AssetManagerUtil.openAsset(registrar, key, getPackage(key)); AssetFileDescriptor fileDescriptor = AssetManagerUtil.openAsset(registrar, key, getPackage(key));
...@@ -208,7 +197,6 @@ public class WeChatThumbnailUtil { ...@@ -208,7 +197,6 @@ public class WeChatThumbnailUtil {
} }
return packageStr; return packageStr;
} }
private static File downloadImage(String url) { private static File downloadImage(String url) {
File result = null; File result = null;
OkHttpClient okHttpClient = new OkHttpClient.Builder().build(); OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
......
...@@ -12,8 +12,6 @@ class MyApp extends StatefulWidget { ...@@ -12,8 +12,6 @@ class MyApp extends StatefulWidget {
} }
class _MyAppState extends State<MyApp> { class _MyAppState extends State<MyApp> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
...@@ -26,9 +24,7 @@ class _MyAppState extends State<MyApp> { ...@@ -26,9 +24,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 {}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
...@@ -41,18 +37,29 @@ class _MyAppState extends State<MyApp> { ...@@ -41,18 +37,29 @@ class _MyAppState extends State<MyApp> {
child: new FlatButton( child: new FlatButton(
onPressed: () { onPressed: () {
var fluwx = Fluwx(); var fluwx = Fluwx();
fluwx.share(WeChatShareMiniProgramModel(
webPageUrl: "http://www.qq.com",
miniProgramType:
WeChatShareMiniProgramModel.MINI_PROGRAM_TYPE_RELEASE,
userName: "gh_d43f693ca31f",
path: '/pages/media',
title: "title",
description: "des",
thumbnail:
'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534532387799&di=12701cc3f20c1a78a5c7524ec33b4c59&imgtype=0&src=http%3A%2F%2Fwww.cssxt.com%2Fuploadfile%2F2017%2F1208%2F20171208110834538.jpg',
));
// 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(
WeChatShareWebPageModel( // WeChatShareWebPageModel(
webPage: "https://www.jianshu.com/", // webPage: "https://www.jianshu.com/",
title: "简书", // title: "简书",
thumbnail: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534532387799&di=12701cc3f20c1a78a5c7524ec33b4c59&imgtype=0&src=http%3A%2F%2Fwww.cssxt.com%2Fuploadfile%2F2017%2F1208%2F20171208110834538.jpg', // thumbnail: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534532387799&di=12701cc3f20c1a78a5c7524ec33b4c59&imgtype=0&src=http%3A%2F%2Fwww.cssxt.com%2Fuploadfile%2F2017%2F1208%2F20171208110834538.jpg',
) // )
).then((result){ // ).then((result){
print("--$result"); // print("--$result");
},onError: (msg){ // },onError: (msg){
print(msg); // print(msg);
}); // });
}, },
child: new Text("share ")), child: new Text("share ")),
), ),
......
{
"editor.quickSuggestions": false
}
\ No newline at end of file
...@@ -95,6 +95,7 @@ class WeChatShareMiniProgramModel extends WeChatShareModel { ...@@ -95,6 +95,7 @@ class WeChatShareMiniProgramModel extends WeChatShareModel {
assert(webPageUrl != null && webPageUrl.isNotEmpty), assert(webPageUrl != null && webPageUrl.isNotEmpty),
assert(userName != null && userName.isNotEmpty), assert(userName != null && userName.isNotEmpty),
assert(path != null && path.isNotEmpty), assert(path != null && path.isNotEmpty),
assert(miniProgramType <3 && miniProgramType > -1),
super( super(
mediaTagName: mediaTagName, mediaTagName: mediaTagName,
messageAction: messageAction, messageAction: messageAction,
...@@ -280,6 +281,7 @@ class WeChatShareWebPageModel extends WeChatShareModel { ...@@ -280,6 +281,7 @@ class WeChatShareWebPageModel extends WeChatShareModel {
String mediaTagName, String mediaTagName,
}) : this.transaction = transaction ?? "text", }) : this.transaction = transaction ?? "text",
assert(webPage != null), assert(webPage != null),
assert(thumbnail != null),
super( super(
mediaTagName: mediaTagName, mediaTagName: mediaTagName,
messageAction: messageAction, messageAction: messageAction,
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论