简体   繁体   English

在 Flutter iOS 中将 jpg 图像转换为 png 图像

[英]Convert jpg image to png image in Flutter iOS

如何将从照片库中选择的 jpg 图像转换为颤振中的 png 图像?

Take a look at the image package .看看图像包 The following is a snippet available in the examples section , which converts JPEG to PNG :以下是示例部分中可用的片段,它将JPEG转换为PNG

import 'dart:io';
import 'package:image/image.dart';
void main() {
  // Read a jpeg image from file.
  Image image = decodeImage(new File('test.jpg').readAsBytesSync());

  // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
  Image thumbnail = copyResize(image, 120);

  // Save the thumbnail as a PNG.
  new File('out/thumbnail-test.png')
    ..writeAsBytesSync(encodePng(thumbnail));
}

First thing you need to do is import IMAGE library.您需要做的第一件事是导入IMAGE库。 Then using similar custom function like below you can convert JPG to PNG然后使用类似的自定义函数,如下所示,您可以将 JPG 转换为 PNG

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:image/image.dart' as Im;
import 'dart:math' as Math;
void jpgTOpng(path) async {
  File imagePath = File(path);
  //get temporary directory
  final tempDir = await getTemporaryDirectory();
  int rand = new Math.Random().nextInt(10000);
  //reading jpg image
  Im.Image image = Im.decodeImage(imagePath.readAsBytesSync());
  //decreasing the size of image- optional
  Im.Image smallerImage = Im.copyResize(image, width:800);
      //get converting and saving in file
  File compressedImage = new File('${tempDir.path}/img_$rand.png')..writeAsBytesSync(Im.encodePng(smallerImage, level:8));     
}

using image library you can do this使用图像库你可以做到这一点

jpegToPng(jpegimage){
new File('output.png')
    ..writeAsBytesSync(encodePng(thumbnail));
}

Many of the suggestions listed are good, I just wanted to add something that may confuse some people.列出的许多建议都很好,我只是想添加一些可能会使某些人感到困惑的东西。 If you're getting black images, see if you have alpha channels in the image.如果您收到黑色图像,请查看图像中是否有 Alpha 通道。 I use the Image package for my purposes, so I just add one during the decode: img.decodeImage(imageFile.readAsBytesSync())..channels = img.Channels.rgba我出于我的目的使用 Image 包,所以我只在解码过程中添加一个: img.decodeImage(imageFile.readAsBytesSync())..channels = img.Channels.rgba

I also use the Image/Paint method to get a Dart UI Image as .png:我还使用 Image/Paint 方法将 Dart UI 图像作为 .png 获取:

img = Image package, thumbnail is an img Image. img = 图片包,thumbnail 是一个img 图片。

import 'dart:ui' as ui;
import 'package:image/image.dart' as img;

    ui.Image imageN;
        try {
          final paint = await PaintingBinding.instance
              .instantiateImageCodec(img.encodePng(thumbnail, level: 0));
          final nextFrame = await paint.getNextFrame();
          imageN = nextFrame.image;
        } catch (e, s) {
          // handle the exception
        }
        return imageN;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM