Flutter图像处理插件pixelbin的使用
Flutter图像处理插件Pixelbin的使用
1. 安装
要使用Pixelbin插件,首先需要通过Pub Package Manager安装。根据你的项目类型(Dart或Flutter),你可以选择以下方式之一进行安装:
-
对于Dart项目:
dart pub add pixelbin
-
对于Flutter项目:
flutter pub add pixelbin
或者,你可以在pubspec.yaml
文件中手动添加依赖项:
dependencies:
pixelbin: ^latest_release_version
2. 创建图像
从URL创建图像
你可以通过提供图像的URL来创建一个PixelBinImage
对象。以下是一个示例代码,展示了如何从URL创建图像并应用一些基本的转换:
import 'package:pixelbin/pixelbin_dart_sdk.dart';
void main() {
final PixelBinImage? imageFromUrl = PixelBin.shared.imageFromUrl(
"https://cdn.pixelbin.io/v2/dummy-cloudname/original/__playground/playground-default.jpeg",
);
if (imageFromUrl != null) {
// 打印编码后的图像URL
debugPrint(imageFromUrl.encoded);
// 从云存储、区域和其他详细信息创建图像
final PixelBinImage imageFromDetails = PixelBin.shared.image(
imagePath: imageFromUrl.imagePath,
cloud: imageFromUrl.cloudName,
transformations: imageFromUrl.transformations,
version: imageFromUrl.version,
);
// 打印编码后的图像URL
debugPrint(imageFromDetails.encoded);
}
}
从云存储创建图像
你还可以通过提供云存储、区域和图像路径来创建图像:
final image = PixelBin.shared.image(
imagePath: "example/logo/apple.jpg",
cloud: "apple_cloud",
zone: "south_asia",
);
// 打印编码后的图像URL
debugPrint(image.encoded); // https://cdn.pixelbin.io/v2/apple_cloud/south_asia/original/example/logo/apple.jpg
3. 应用转换
Pixelbin支持多种图像转换操作,例如调整大小、压缩、旋转等。以下是一些常见的转换操作示例:
调整大小
final resizeTransformation = Transformation.tResize(height: 200, width: 200);
image.addTransformation(resizeTransformation);
// 或者一次性应用多个转换
image.addTransformations([resizeTransformation, blurTransformation]);
压缩
final compressTransformation = Transformation.tCompress(quality: 80);
image.addTransformation(compressTransformation);
模糊
final blurTransformation = Transformation.tBlur(sigma: 0.3, dpr: 1);
image.addTransformation(blurTransformation);
移除背景
final eraseTransformation = Transformation.eraseBg(
industryType: EraseIndustryType.general,
addShadow: false,
refine: true,
);
image.addTransformation(eraseTransformation);
获取最终的图像URL
final outputUrl = image.encoded;
debugPrint("outputUrl: $outputUrl");
4. 上传图像
要上传图像到Pixelbin,你需要生成一个签名的URL和相关的元数据。以下是一个完整的上传示例:
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:pixelbin/pixelbin_dart_sdk.dart';
Future<void> _callPixelBinUpload(File file) async {
try {
final fields = {
"x-pixb-meta-assetdata":
"{\"orgId\":5814399,\"type\":\"file\",\"name\":\"filename.jpeg\",\"path\":\"path/to/containing/folder\",\"fileId\":\"path/to/containing/folder/filename.jpeg\",\"format\":\"jpeg\",\"s3Bucket\":\"erase-erase-erasebg-assets\",\"s3Key\":\"uploads/vijay-744d3d/original/71ea75a1-eeb6-41ce-b5a1-093d248dddf9.jpeg\",\"access\":\"public-read\",\"tags\":[\"tag1\",\"tag2\"],\"metadata\":{\"source\":\"signedUrl\",\"publicUploadId\":\"2a2994a1-75ec-42b9-b67f-34a96c514890\"},\"overwrite\":false,\"filenameOverride\":true}"
};
final signedDetails = SignedDetails(
url: "SIGNED_URL", // 替换为实际的签名URL
fields: fields,
);
final PixelBinImage? uploadResponse = await PixelBin.shared.upload(
file: file,
signedDetails: signedDetails,
);
// 打印上传后的图像URL
debugPrint("Response: ${uploadResponse?.encoded}");
} catch (e) {
// 打印错误信息
debugPrint("Error: ${e.toString()}");
}
}
5. 完整示例Demo
以下是一个完整的Flutter应用程序示例,展示了如何使用Pixelbin插件进行图像选择、上传和处理:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pixelbin/pixelbin_dart_sdk.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const ImagePickerWidget(),
);
}
}
class ImagePickerWidget extends StatefulWidget {
const ImagePickerWidget({super.key});
[@override](/user/override)
ImagePickerWidgetState createState() => ImagePickerWidgetState();
}
class ImagePickerWidgetState extends State<ImagePickerWidget> {
File? _imageFile;
final ImagePicker _picker = ImagePicker();
Future<void> _pickImage() async {
final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
setState(() {
_imageFile = File(pickedFile.path);
});
}
}
Future<void> _callPixelBinUpload() async {
if (_imageFile == null) return;
try {
final fields = {
"x-pixb-meta-assetdata":
"{\"orgId\":5814399,\"type\":\"file\",\"name\":\"filename.jpeg\",\"path\":\"path/to/containing/folder\",\"fileId\":\"path/to/containing/folder/filename.jpeg\",\"format\":\"jpeg\",\"s3Bucket\":\"erase-erase-erasebg-assets\",\"s3Key\":\"uploads/vijay-744d3d/original/71ea75a1-eeb6-41ce-b5a1-093d248dddf9.jpeg\",\"access\":\"public-read\",\"tags\":[\"tag1\",\"tag2\"],\"metadata\":{\"source\":\"signedUrl\",\"publicUploadId\":\"2a2994a1-75ec-42b9-b67f-34a96c514890\"},\"overwrite\":false,\"filenameOverride\":true}"
};
final signedDetails = SignedDetails(
url: "SIGNED_URL", // 替换为实际的签名URL
fields: fields,
);
final PixelBinImage? uploadResponse = await PixelBin.shared.upload(
file: _imageFile!,
signedDetails: signedDetails,
);
// 打印上传后的图像URL
debugPrint("Response: ${uploadResponse?.encoded}");
} catch (e) {
// 打印错误信息
debugPrint("Error: ${e.toString()}");
}
}
[@override](/user/override)
void initState() {
super.initState();
var pixelBin = PixelBin.shared;
final PixelBinImage? imageFromUrl = pixelBin.imageFromUrl(
"https://cdn.pixelbin.io/v2/dummy-cloudname/erase.bg(shadow:false,r:true,i:general)~af.remove()~t.blur(s:0.3,dpr:1.0)/__playground/playground-default.jpeg",
);
debugPrint(imageFromUrl?.encoded);
if (imageFromUrl != null) {
final PixelBinImage imageFromDetails = pixelBin.image(
imagePath: imageFromUrl.imagePath,
cloud: imageFromUrl.cloudName,
transformations: imageFromUrl.transformations,
version: imageFromUrl.version,
);
debugPrint(imageFromDetails.encoded);
final eraseTransformation = Transformation.eraseBg();
final resizeTransformation = Transformation.tResize(width: 200);
final blurTransformation = Transformation.tBlur(dpr: 5);
imageFromDetails.addTransformation(eraseTransformation);
imageFromDetails.addTransformation(resizeTransformation);
imageFromDetails.addTransformation(blurTransformation);
final outputUrl = imageFromDetails.encoded;
debugPrint("imageDetails: output: $outputUrl");
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Image Picker Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_imageFile != null
? Image.file(
_imageFile!,
height: 300,
width: 300,
)
: Container(
height: 300,
width: 300,
color: Colors.grey[300],
child: Icon(
Icons.image,
size: 100,
color: Colors.grey[700],
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _pickImage,
child: const Text('Pick Image from Gallery'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _callPixelBinUpload,
child: const Text('Upload File'),
),
],
),
),
);
}
}
更多关于Flutter图像处理插件pixelbin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter图像处理插件pixelbin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter中使用pixelbin
插件进行图像处理的示例代码。pixelbin
插件通常用于对图像进行像素级别的处理,比如调整图像尺寸、裁剪等。以下是一个基本的示例,展示了如何使用pixelbin
插件来加载和处理图像。
首先,确保你已经在pubspec.yaml
文件中添加了pixelbin
插件的依赖:
dependencies:
flutter:
sdk: flutter
pixelbin: ^最新版本号 # 请替换为实际可用的最新版本号
然后,你可以在你的Flutter项目中按照以下步骤使用pixelbin
插件:
- 导入必要的包:
import 'package:flutter/material.dart';
import 'package:pixelbin/pixelbin.dart';
import 'dart:typed_data';
import 'dart:ui' as ui;
- 定义一个方法来加载和处理图像:
Future<Uint8List?> loadAndProcessImage(String imagePath) async {
// 加载图像文件
final Uint8List? imageBytes = await rootBundle.load(imagePath);
if (imageBytes == null) {
return null;
}
// 创建ImageProvider
final ui.Codec codec = await ui.instantiateImageCodec(imageBytes!);
final ui.FrameInfo frameInfo = await codec.getNextFrame();
final ui.Image image = frameInfo.image;
// 转换为PixelData
final PixelData pixelData = PixelData.fromImageProvider(
imageProvider: MemoryImage(imageBytes!),
scale: 1.0,
);
// 调用PixelBin的resize方法(示例:将图像尺寸调整为原来的一半)
final PixelBin pixelBin = PixelBin(pixelData);
final Uint8List resizedImageBytes = await pixelBin.resize(
width: pixelData.width ~/ 2,
height: pixelData.height ~/ 2,
);
return resizedImageBytes;
}
- 在UI中显示处理后的图像:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('PixelBin Example'),
),
body: FutureBuilder<Uint8List?>(
future: loadAndProcessImage('assets/your_image.png'), // 请替换为你的图像路径
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error loading image'));
} else if (snapshot.data != null) {
return Center(
child: Image.memory(snapshot.data!),
);
} else {
return Center(child: Text('No image data'));
}
},
),
),
);
}
}
在上面的代码中:
- 我们首先通过
rootBundle.load
方法加载了图像文件。 - 然后,我们使用
ui.instantiateImageCodec
和ui.FrameInfo
来解码图像并获取图像帧。 - 接着,我们使用
PixelData.fromImageProvider
方法将图像转换为PixelData
对象。 - 使用
PixelBin
的resize
方法将图像尺寸调整为原来的一半。 - 最后,我们使用
FutureBuilder
来异步加载和处理图像,并在UI中显示处理后的图像。
请注意,pixelbin
插件的具体API可能会随着版本的更新而有所变化,因此建议查看最新的官方文档以获取最准确的信息。