gpt4 book ai didi

image - 上传前调整图像大小

转载 作者:IT王子 更新时间:2023-10-29 06:51:33 28 4
gpt4 key购买 nike

我需要在上传到服务器之前调整图片大小。

我正在使用 io 和图像包。

import 'dart:io';  
import 'package:image/image.dart' as Img;

使用这个函数

uploadImages(File image_File) async {

Img.Image image_temp = Img.decodeImage(image_File.readAsBytesSync());

Img.Image resized_img = Img.copyResize(image_temp, 800);

File resized_file = File('resized_img.jpg')
..writeAsBytesSync(Img.encodeJpg(resized_img));

var stream = new http.ByteStream(DelegatingStream.typed(resized_file.openRead()));
var length = await resized_file.length();

var uri = Uri.parse("https://myserver.com/upload.php");

var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: p.basename("resized_image.jpg"));


request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}

当我运行这段代码时,应用程序只是卡住并且图像没有上传到服务器。

最佳答案

无需将其写入文件;您可以直接从内存发送调整大小的图像。

uploadImages(File image_File) async {
img.Image image_temp = img.decodeImage(image_File.readAsBytesSync());
img.Image resized_img = img.copyResize(image_temp, 800);

var request = new http.MultipartRequest(
'POST',
Uri.parse('https://myserver.com/upload.php'),
);
var multipartFile = new http.MultipartFile.fromBytes(
'file',
img.encodeJpg(resized_img),
filename: 'resized_image.jpg',
contentType: MediaType.parse('image/jpeg'),
);

request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}

注意:导入包时,应使用小写标签(即 img)。您还需要导入 package:http_parser 以获取 MediaType

关于image - 上传前调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603614/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com