【问题标题】:How to convert Camera Image to Image in Flutter?如何在 Flutter 中将相机图像转换为图像?
【发布时间】:2019-08-22 06:25:48
【问题描述】:

我想将 Flutter 中相机插件的函数 startImageStream() 中的相机图像转换为图像以裁剪该图像,但我只能找到转换为 FirebaseVisionImage 的方法。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    编辑彩色图像

    如果我明白你的意思。您正在尝试使用 YUV420 格式。
    以下是来自https://github.com/flutter/flutter/issues/26348的代码sn-p

    const shift = (0xFF << 24);
    Future<Image> convertYUV420toImageColor(CameraImage image) async {
          try {
            final int width = image.width;
            final int height = image.height;
            final int uvRowStride = image.planes[1].bytesPerRow;
            final int uvPixelStride = image.planes[1].bytesPerPixel;
    
            print("uvRowStride: " + uvRowStride.toString());
            print("uvPixelStride: " + uvPixelStride.toString());
    
            // imgLib -> Image package from https://pub.dartlang.org/packages/image
            var img = imglib.Image(width, height); // Create Image buffer
    
            // Fill image buffer with plane[0] from YUV420_888
            for(int x=0; x < width; x++) {
              for(int y=0; y < height; y++) {
                final int uvIndex = uvPixelStride * (x/2).floor() + uvRowStride*(y/2).floor();
                final int index = y * width + x;
    
                final yp = image.planes[0].bytes[index];
                final up = image.planes[1].bytes[uvIndex];
                final vp = image.planes[2].bytes[uvIndex];
                // Calculate pixel color
                int r = (yp + vp * 1436 / 1024 - 179).round().clamp(0, 255);
                int g = (yp - up * 46549 / 131072 + 44 -vp * 93604 / 131072 + 91).round().clamp(0, 255);
                int b = (yp + up * 1814 / 1024 - 227).round().clamp(0, 255);     
                // color: 0x FF  FF  FF  FF 
                //           A   B   G   R
                img.data[index] = shift | (b << 16) | (g << 8) | r;
              }
            }
    
            imglib.PngEncoder pngEncoder = new imglib.PngEncoder(level: 0, filter: 0);
            List<int> png = pngEncoder.encodeImage(img);
            muteYUVProcessing = false;
            return Image.memory(png);  
          } catch (e) {
            print(">>>>>>>>>>>> ERROR:" + e.toString());
          }
          return null;
      }
    

    【讨论】:

    • 谢谢您,先生。它很棒
    • 您好,先生。你试过这个转换功能了吗?我尝试在转换后显示图像,但新图像没有颜色
    • 我已经更新了我的答案。你能再测试一下吗?让我知道结果。非常感谢你。如果效果不好,我会删除这个答案。
    • 无法在 ios RangeError (index): Invalid value: Only valid value is 0: 1 中工作,因为 bytesPerPixel 为空,而 image.planes.length = 1 在 IOS 中。还有其他方法吗?请帮帮我。
    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2022-12-12
    • 2020-10-03
    • 1970-01-01
    • 2020-03-06
    相关资源
    最近更新 更多