Flutter:Remove.bg 去背APP

Yanwei Liu
4 min readJun 2, 2020

--

開發這個APP最困難的地方是研究如何使用http去串接Remove.bg的API,花了很多時間研究。

記得先到https://www.remove.bg/註冊帳號申請api

參考資料:

程式運作流程:

啟動APP -> 點擊拍照 -> 保存拍攝圖片 -> 用http套件串接去背API -> post圖片(普通圖片轉成base64Image格式) -> 下載去背後圖片(response.bodyBytes) ->預覽成果

程式碼:

main.dart

CameraTaken.dart

preview_screen.dart

串接API關鍵處:

以下程式進行了HTTP API的POST(圖片上傳,base64格式)、去背成功圖片下載(response.bodyBytes)

initState() {
_asyncMethod();
super.initState();
}
_asyncMethod()async{
List<int> imageBytes = File(widget.imagePath).readAsBytesSync();
print(imageBytes);
String base64Image = base64Encode(imageBytes);
final body = {"image_file_b64": base64Image, "size": "auto"};
final headers = {"X-API-Key": "put_API_Key_Here"};
final response = await http.post('https://api.remove.bg/v1.0/removebg',
body: body,
headers: headers);

if (response.statusCode == 200) {
var documentDirectory = await getApplicationDocumentsDirectory();
var firstPath = documentDirectory.path + "/images";
var filePathAndName = documentDirectory.path + '/images/pic.jpg';
await Directory(firstPath).create(recursive: true);
File file2 = new File(filePathAndName);
file2.writeAsBytesSync(response.bodyBytes);
setState(() {
imageData = filePathAndName;
dataLoaded = true;
});
} else {
throw Exception('Failed to do network requests: Error Code: ${response.statusCode}\nBody: ${response.body}');
}
}
String imageData;
bool dataLoaded = false;

--

--

Responses (1)