Unity使用OpenCVForUnity加载和保存webp格式的图片

public static class Texture2DExtend
{
    public static void LoadFromWebp(this Texture2D texture2D, byte[] data)
    {
        MatOfByte matOfByte = new MatOfByte(data);
        OpenCVForUnity.Mat mat = Imgcodecs.imdecode(matOfByte, Imgcodecs.IMREAD_COLOR);

        texture2D.Resize(mat.cols(), mat.rows(), TextureFormat.RGBA32, false);
        OpenCVForUnity.Utils.matToTexture2D(mat, texture2D);

        matOfByte.Dispose();
        mat.Dispose();
    }

    public static byte[] EncodeToWebp(this Texture2D texture2D, int quality = 75)
    {
        OpenCVForUnity.Mat mat = new OpenCVForUnity.Mat(texture2D.height, texture2D.width, OpenCVForUnity.CvType.CV_8UC4);
        MatOfInt matOfInt = new MatOfInt(Imgcodecs.CV_IMWRITE_WEBP_QUALITY, quality);
        MatOfByte matOfByte = new MatOfByte();

        OpenCVForUnity.Utils.texture2DToMat(texture2D, mat);
        Imgcodecs.imencode(".webp", mat, matOfByte, matOfInt);
        byte[] byteArray = matOfByte.toArray();

        mat.Dispose();
        matOfInt.Dispose();
        matOfByte.Dispose();

        return byteArray;
    }
}

 

posted on 2023-08-08 14:39  Jason_c  阅读(399)  评论(0编辑  收藏  举报