opencv 图像格式转换

extern "C" _declspec(dllexport) BYTE* __stdcall ImageConvert(BYTE* imageData, int imageDataSize, const char* format, int* returnSize)
{
    vector<uchar> data;
    for (int i = 0; i < imageDataSize; ++i) {
        data.push_back(imageData[i]);
    }

    cv::Mat image = cv::imdecode(data, CV_LOAD_IMAGE_COLOR);
    std::vector<uchar> buf;
    imencode(format, image, buf);

    *returnSize = buf.size();
    BYTE* result = new BYTE[*returnSize];
    for (int i = 0; i < *returnSize; i++)
        result[i] = buf[i];
    return result;
}

 JAVA调用代码:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.sun.jna.Library;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

public class Program {
    
    public interface Lib extends Library
    {
        public Pointer ImageConvert(Pointer data, int dataSize, String format , Pointer resultSize);
    }
    
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws IOException {
        Lib lib = (Lib) Native.loadLibrary("..\\OpenCVDemo.dll", Lib.class);
        byte[] data = Files.readAllBytes(Paths.get("..\\01.tif"));
        Pointer ptr = new Memory(data.length);
        ptr.write(0, data, 0, data.length);
        Pointer returnSize = new Memory(4);
        Pointer result = lib.ImageConvert(ptr, data.length, ".png" , returnSize);
        byte[] resultData = result.getByteArray(0, returnSize.getInt(0));
        Files.write(Paths.get("..\\01.png"), resultData);
        System.out.println("ok");
    }

}

追加:

下面这个可能更高效:

extern "C" _declspec(dllexport) BYTE* __stdcall ImageConvert(BYTE* imageData, int imageDataSize, const char* format, int* returnSize)
{
    //convert byte[] to vector<uchar>
    std::vector<uchar> data(imageData, imageData + imageDataSize);

    //convert image format
    cv::Mat image = cv::imdecode(data, CV_LOAD_IMAGE_COLOR);
    std::vector<uchar> buf;
    imencode(format, image, buf);

    //covert vector<uchar> to byte[]
    *returnSize = buf.size();
    BYTE* result = new BYTE[*returnSize];
    std::copy(buf.begin(), buf.end(), result);

    return result;
}

 

posted on 2021-01-13 13:11  空明流光  阅读(772)  评论(0编辑  收藏  举报

导航