Flutterで効率的な画像圧縮を実現
Flutterで効率的な画像圧縮を実現
概要
モバイルアプリ開発中に、画像のサイズを圧縮して、アプリがユーザーの携帯電話のストレージを節約し、通信量を減らすための必要があります。今回は、Flutterを使用して効率的な画像圧縮を実現します。
開発ステップ
このセクションでは、Flutterを使用して画像圧縮ツールを開発するステップを紹介します。全体の開発プロセスは以下の通りです:
- 関連依存ライブラリの導入
- メイン機能の実装
- UIとインタラクションロジックの実装
1. 関連依存ライブラリの導入
Flutterでは、pubspec.yaml
ファイルを使用して依存ライブラリとコードパッケージを管理します。今回使用する画像圧縮機能には、以下の二つの依存ライブラリを使用します:
-
image_picker
: アルバムやカメラから画像を選択するためのライブラリ。 -
image
: 強力で柔軟な画像処理ライブラリ。
2. メイン機能の実装
この部分では、画像圧縮ツールの主な機能を実装します。主に以下の内容を含みます:
- 画像サイズの圧縮
- 画像品質の圧縮
- 圧縮後の画像ファイルの生成
2.1 画像サイズの圧縮
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image/image.dart' as Img;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: 'Image Compressor',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Image Compressor'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late File _imageFile;
TextEditingController _widthController = TextEditingController();
TextEditingController _heightController = TextEditingController();
Future<void> _pickImage(ImageSource source) async {
final pickedFile = await ImagePicker().pickImage(
source: source,
imageQuality: 100
);
setState(() {
if (pickedFile != null) {
_imageFile = File(pickedFile.path);
} else {
print(‘No image selected.’);
}
});
}
void _compressImage() async {
if (_imageFile == null) {
return;
}
int width = int.parse(_widthController.text);
int height = int.parse(_heightController.text);
Img.Image image = Img.decodeImage(await _imageFile.readAsBytes())!;
Img.Image resizedImage = Img.copyResize(image, width: width, height: height);
String tempPath = (await getTemporaryDirectory()).path;
File compressedImageFile = File('$tempPath/compressed_image.jpg');
compressedImageFile.writeAsBytesSync(Img.encodeJpg(resizedImage));
}
画像圧縮の第一歩は、画像のサイズを調整することです。Flutterでは、image
ライブラリのResize
関数を使用してこの手順を完了します。
2.2 画像品質の圧縮
Img.Image image = Img.decodeImage(await _imageFile.readAsBytes())!;
int quality = 80;
List<int> compressedImage = Img.encodeJpg(image, quality: quality);
画像圧縮の第二歩は、画像の品質を調整することです。Flutterでは、image
ライブラリのencodeJpg
関数を使用してこの手順を完了します。
2.3 圧縮後の画像ファイルの生成
String tempPath = (await getTemporaryDirectory()).path;
File compressedImageFile = File('$tempPath/compressed_image.jpg');
compressedImageFile.writeAsBytesSync(compressedImage);
圧縮後の画像をファイルに保存します。Flutterでは、File
クラスのwriteAsBytesSync
関数を使用してバイト配列をファイルに書き込みます。
3. UIとインタラクションロジックの実装
FlatButton(
child: Text('Select Image'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Select Image Source'),
actions: <Widget>[
FlatButton(
child: Text('Camera'),
onPressed: () {
Navigator.pop(context);
_pickImage(ImageSource.camera);
},
),
FlatButton(
child: Text('Gallery'),
onPressed: () {
Navigator.pop(context);
_pickImage(ImageSource.gallery);
},
),
],
);
},
);
},
),
Flutterのウィジェットビルダーを使用して簡単なUIを作成します。私たちのケースでは、画像を選択するボタン、画像の幅と高さを入力するテキストボックス、画像圧縮の操作をトリガーするボタン、圧縮後の画像を表示するイメージビューアが必要です。
画像の幅と高さを入力するテキストボックス
TextField(
controller: _widthController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Enter Width',
),
),
TextField(
controller: _heightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: ‘Enter Height’,
),
),
画像圧縮の操作をトリガーするボタン
RaisedButton(
child: Text('Compress Image'),
onPressed: () {
_compressImage();
},
),
圧縮後の画像を表示するイメージビューア
Expanded(
child: Container(
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue,
),
),
child: _imageFile == null
? Text('No image selected.')
: Image.file(_imageFile),
),
),
まとめ
Flutterを使用して効率的な画像圧縮ツールを開発する方法を学びました。image_picker
とimage
ライブラリを使用して画像圧縮の主要機能を実装し、UIデザインを行いました。
Discussion