# 备份部分代码

MainActivity.java 实用源生安卓来处理模糊,但是还是慢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.li.ying;  

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import android.renderscript.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "image_processing";

@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
if (call.method.equals("blurImage")) {
String imagePath = call.argument("imagePath");
int radius = call.argument("radius");
try {
result.success(blurImage(imagePath, radius));
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
result.notImplemented();
}
}
);
}

private String blurImage(String imagePath, int radius) throws IOException {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
RenderScript rs = RenderScript.create(this);
Allocation input = Allocation.createFromBitmap(rs, bitmap);
Allocation output = Allocation.createTyped(rs, input.getType());
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

// 多次应用高斯模糊
for (int i = 0; i < 5; i++) {
script.setRadius(radius);
script.setInput(input);
script.forEach(output);
output.copyTo(bitmap);
input.copyFrom(bitmap);
}

rs.destroy();

File outputDir = getCacheDir();
File outputFile = File.createTempFile("blurred_", ".png", outputDir);
FileOutputStream out = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();

return outputFile.getAbsolutePath();
}

}

main.dart 调用源生安卓

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// static const platform = MethodChannel('image_processing');  
//
// 这种方法 调用了安卓原生代码 速度更快 但是快不过缩小图片模糊
// 并且radius最大25 模糊效果不尽人意
// File? _blurredImage;
//
// Future<void> _blurImage(String imagePath) async {
// try {
// final String blurredImagePath = await platform.invokeMethod(
// 'blurImage',
// {'imagePath': imagePath, 'radius': 25},
// );
// setState(() {
// _blurredImage = File(blurredImagePath);
// });
// } on PlatformException catch (e) {
// print("Failed to blur image: '${e.message}'.");
// }
// }

更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

有李说不清 微信支付

微信支付

有李说不清 支付宝

支付宝

有李说不清 贝宝

贝宝