如何将图像转换为文件? [英] How to convert Image to File?

查看:92
本文介绍了如何将图像转换为文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图像保存到未从图库或照相机中获取图像的设备的正确方法是什么?

What is the correct way to save Image to device where the image is not taken from gallery or camera?

在PageA中,有一个相机按钮,允许用户捕获图像。捕获图像后,它将转到PageB(EditImagePage)。用户完成图像编辑后,它将返回到PageA,并将图像保存到设备。

In PageA, there is a camera button allow user to capture image. Once image is captured, it will go to PageB (EditImagePage). Once user done editing the image, it will back to PageA, and save the image to device.

PageA

  @override
  userImage(File images) async {  // when user has captured image, it will run this code
    if (images != null) {
      Image image = await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => EditImagePage(images.path), // go to edit image page
          ));
         // convert image to File
         // call copyImage function
    } else {

    }
  }

PageB

 IconButton(
          icon: Icon(Icons.check),
          onPressed: () async {
            Uint8List bytes = await _controller.exportAsPNGBytes();
            var image = Image.memory(bytes);
            return Navigator.pop(context, image);  // bring Image back to PageA
          }),

我有这段代码用于将图像保存到设备。如何将其更改为File?

I have this code used to save the Image to device. How can change it to File?

Future<File> copyImage(File image) async {
        var savedDir = await getApplicationDocumentsDirectory();
        String appDocPath = savedDir.path;
        var fileName = FileUtils.basename(image.path);
        return await image.copy('$appDocPath/' + '$fileName');
      }


推荐答案

您可以将图像存储到设备内部存储,将图像,资产图像转换为文件,然后存储到设备存储中。

You can store image to device internal storage, convert image, assets image to File and store into device storage.

首先获取图像路径,创建文件并写入imageAsBytes。

First of get your image path, make to file and writeAsBytes for image.

您可以编写以下代码:

import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart' show rootServices;
import 'package:path_provider/path_provider.dart';

Future<File> convertImageToFile(String imagePath) async {
  final byteData = await rootServices.load('assets/$imagePath');

  final file = File('${(await getTemporaryDirectory()).path}/$imagePath');
  await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

  return file;
}

需要存储访问权限,请不要忘记它。

Need to storage access permission, don't forgot it.

这篇关于如何将图像转换为文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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