Flutter-调整网络映像大小 [英] Flutter - Resize network image

查看:70
本文介绍了Flutter-调整网络映像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不事先将图像写入存储的情况下调整图像大小?我正在使用一个pdf库,该库需要图像的字节.

我要做的是获取带有http.get的图像,然后获取将其放入pdf中的字节.问题是我需要先调整图像大小,然后再将其放入pdf中.

我唯一拥有的是图片的网址或uint8list

 响应响应=等待http.get(imageUrl);Uint8List imgBytes = response.bodyBytes; 

稍后:

  Image(PdfImage.file(pdf.document,字节:imageBytes)), 

我使用的PDF库:

完整代码

  import'dart:typed_data';将'dart:ui'导入为ui;导入'package:flutter/material.dart';导入'package:http/http.dart'为http;导入'dart:io';void main(){runApp(MyApp());}MyApp类扩展了StatelessWidget {@override窗口小部件build(BuildContext context){返回MaterialApp(标题:"Flutter演示",主题:ThemeData(primarySwatch:Colors.blue,visualDensity:VisualDensity.adaptivePlatformDensity,),主页:MyHomePage(标题:"Flutter演示首页"),);}}类MyHomePage扩展了StatefulWidget {MyHomePage({Key key,this.title}):超级(key:key);最终的字符串标题;@override_MyHomePageState createState()=>_MyHomePageState();}类_MyHomePageState扩展State< MyHomePage>{Uint8List targetlUinit8List;Uint8List originalUnit8List;void _resizeImage()异步{字符串imageUrl ='https://picsum.photos/250?image=9';http.Response response =等待http.get(imageUrl);originalUnit8List = response.bodyBytes;ui.Image originalUiImage =等待encodeImageFromList(originalUnit8List);ByteData originalByteData =等待originalUiImage.toByteData();print('原始图片的ByteData大小为$ {originalByteData.lengthInBytes}');var codec = await ui.instantiateImageCodec(originalUnit8List,targetHeight:50,targetWidth:50);var frameInfo =等待codec.getNextFrame();ui.Image targetUiImage = frameInfo.image;ByteData targetByteData =等待targetUiImage.toByteData(format:ui.ImageByteFormat.png);print('目标图像的ByteData大小为$ {targetByteData.lengthInBytes}');targetlUinit8List = targetByteData.buffer.asUint8List();setState((){});}@override窗口小部件build(BuildContext context){返回脚手架(appBar:AppBar(标题:文本(widget.title),),身体:中心(子:列(mainAxisAlignment:MainAxisAlignment.center,子代:< Widget> [originalUnit8List == null?容器():Image.memory(originalUnit8List),targetlUinit8List == null?容器():Image.memory(targetlUinit8List),],),),floatActionButton:FloatingActionButton(onPressed:_resizeImage,工具提示:调整大小",子级:Icon(Icons.add),),);}} 

Is there a way to resize an image without having it previously written to storage? I am using a pdf library that for the images needs the bytes of it.

What I do is get image with an http.get and I get the bytes to put it in the pdf. The problem is that I need to resize the image BEFORE putting it in the pdf.

The only thing I have is the url of the image or the uint8list

Response response = await http.get(imageUrl);
Uint8List imgBytes = response.bodyBytes;

Later:

Image(
    PdfImage.file(pdf.document,
    bytes: imageBytes)
),

Pdf lib I use: https://pub.dev/packages/pdf

解决方案

You can copy paste run full code below
You can use ui.instantiateImageCodec and specify targetHeight and targetWidth
You can see output image size become smaller after resize

code snippet

    String imageUrl = 'https://picsum.photos/250?image=9';
    http.Response response = await http.get(imageUrl);
    originalUnit8List = response.bodyBytes;

    ui.Image originalUiImage = await decodeImageFromList(originalUnit8List);
    ByteData originalByteData = await originalUiImage.toByteData();
    print('original image ByteData size is ${originalByteData.lengthInBytes}');

    var codec = await ui.instantiateImageCodec(originalUnit8List,
        targetHeight: 50, targetWidth: 50);
    var frameInfo = await codec.getNextFrame();
    ui.Image targetUiImage = frameInfo.image;

    ByteData targetByteData =
        await targetUiImage.toByteData(format: ui.ImageByteFormat.png);
    print('target image ByteData size is ${targetByteData.lengthInBytes}');
    targetlUinit8List = targetByteData.buffer.asUint8List();

output of working demo

I/flutter (17023): original image ByteData size is 250000
I/flutter (17023): target image ByteData size is 4060

working demo

full code

import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:io';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Uint8List targetlUinit8List;
  Uint8List originalUnit8List;

  void _resizeImage() async {
    String imageUrl = 'https://picsum.photos/250?image=9';
    http.Response response = await http.get(imageUrl);
    originalUnit8List = response.bodyBytes;

    ui.Image originalUiImage = await decodeImageFromList(originalUnit8List);
    ByteData originalByteData = await originalUiImage.toByteData();
    print('original image ByteData size is ${originalByteData.lengthInBytes}');

    var codec = await ui.instantiateImageCodec(originalUnit8List,
        targetHeight: 50, targetWidth: 50);
    var frameInfo = await codec.getNextFrame();
    ui.Image targetUiImage = frameInfo.image;

    ByteData targetByteData =
        await targetUiImage.toByteData(format: ui.ImageByteFormat.png);
    print('target image ByteData size is ${targetByteData.lengthInBytes}');
    targetlUinit8List = targetByteData.buffer.asUint8List();

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            originalUnit8List == null
                ? Container()
                : Image.memory(originalUnit8List),
            targetlUinit8List == null
                ? Container()
                : Image.memory(targetlUinit8List),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _resizeImage,
        tooltip: 'Resize',
        child: Icon(Icons.add),
      ),
    );
  }
}

这篇关于Flutter-调整网络映像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆