我正在开发一个Flutter应用程序,可以上传到PostgreSQL数据库并从中获取数据。我使用pubspec.yaml文件中的postgres:^2.3.2。
首先,我将图像转换为base64。然后,我将图像作为BYTEA上传到数据库。
当我从数据库中查询图像数据时,它为我提供了一个整数列表。我搜索了一下网页,发现我必须将该列表转换为Uint8List。将其转换为Uint8List后,我必须使用Image.memory方法将Uint8List转换为图像小部件。但是当我这样做时,我在控制台上得到了这个错误:
═══════ Exception caught by image resource service ════════════════════════════
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data
When the exception was thrown, this was the stack
#0 _futurize (dart:ui/painting.dart:5326:5)
#1 ImageDescriptor.encoded (dart:ui/painting.dart:5194:12)
#2 instantiateImageCodec (dart:ui/painting.dart:2048:60)
<asynchronous suspension>
════════════════════════════════════════════════════════════════════════════════
字符串
设备上的图像:Device screenshot
代码如下:
import 'dart:typed_data';
import 'package:flutter/material.dart';
class ShowImage extends StatefulWidget {
const ShowImage({Key? key}) : super(key: key);
@override
_ShowImageState createState() => _ShowImageState();
}
class _ShowImageState extends State<ShowImage> {
dynamic _image;
Map data = {};
void setImage() async {
GetImage getImgObj = GetImage(connection: data['connection']);
dynamic imgBytes = await getImgObj.getImage();
print(imgBytes.runtimeType);
setState(() {
_image = Image.memory(imgBytes);
});
}
@override
Widget build(BuildContext context) {
data = ModalRoute.of(context)!.settings.arguments as Map;
// setImage();
return Scaffold(
appBar: AppBar(
title: Text("Show Image"),
centerTitle: true,
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(18.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: () {
setImage();
},
child: Text("Get Image"),
),
SizedBox(height: 10.0),
Container(
width: 100,
height: 350,
decoration:
BoxDecoration(border: Border.all(color: Colors.grey)),
child: _image == null
? Align(
alignment: Alignment.center,
child: Text(
"Image not selected",
textAlign: TextAlign.center,
),
)
: Align(
alignment: Alignment.center,
child: _image,
),
),
],
),
),
),
);
}
}
class GetImage {
var connection;
GetImage({this.connection});
Future<dynamic> getImage() async {
int itemId = 1;
String query = "SELECT img FROM lawbreach WHERE lid = $itemId;";
List<dynamic> results = await this.connection.query(query);
final bytes = Uint8List.fromList(results[0][0]);
return bytes;
}
}
型
我试着搜索网络的每一个角落,但找不到任何解决方案。希望,这里有人能回答我的问题:)
2条答案
按热度按时间ybzsozfc1#
Image widget抛出“Invalid image data”异常的原因是您尝试加载的base64无效。您需要检查您下载的base64编码图像是否再次编码为base64。在将下载的base64编码图像加载到widget之前,请对其进行解码。
字符串
au9on6nz2#
我如何解决我自己的,我提取的图像,因为它是在zip文件夹,并转到pubspect.yaml
assets: - images/image_22.jpg
然后在我的小部件,我然后添加child: Image.asset('images/image_22.jpg')