好的,所以这是我们所做的一些黑客行为,但并没有达到我们所需要的,因为它创建了一个副本:
Bitmap^ MyClass::GetBitmapImageDestination(uchar *imageBytes, int imageWidth, int imageHeight, ColorMode colorMode) {
int channels = colorMode == ColorMode::Gray8 ? 1 : 4;
DataWriter^ writer = ref new DataWriter();
Platform::ArrayReference<uchar, 1> tempArray(imageBytes, imageWidth * imageHeight * 4);
writer->WriteBytes(tempArray);
IBuffer^ byteBuffer = writer->DetachBuffer();
return ref new Bitmap(Windows::Foundation::Size((float)imageWidth, (float)imageHeight), colorMode, (uint)(imageWidth * channels), byteBuffer);
}
但经过一番思考,我们决定尝试使用我们自己的实现来继承 IBuffer。感谢 jmorrill 对 MSDN 上这篇文章的帮助:
https://social.msdn.microsoft.com/Forums/en-US/816e5718-224d-4bb7-bf06-230e9c6cda5b/how-to-create-an-ibuffer-from-scratch?forum=winappswithnativecode
这是我们对 IBuffer 的实现:
class ImageBuffer : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
ABI::Windows::Storage::Streams::IBuffer,
Windows::Storage::Streams::IBufferByteAccess >
{
public:
virtual ~ImageBuffer()
{
}
STDMETHODIMP RuntimeClassInitialize(UINT totalSize, UCHAR* data)
{
_imageLength = totalSize;
_imageData = data;
return S_OK;
}
STDMETHODIMP Buffer( byte **value)
{
*value = &_imageData[0];
return S_OK;
}
STDMETHODIMP get_Capacity(UINT32 *value)
{
*value = _imageLength;
return S_OK;
}
STDMETHODIMP get_Length(UINT32 *value)
{
*value = _imageLength;
return S_OK;
}
STDMETHODIMP put_Length(UINT32 value)
{
if(value > _imageLength)
return E_INVALIDARG;
_imageLength = value;
return S_OK;
}
private:
UINT32 _imageLength;
UCHAR *_imageData;
};
我们使用互操作创建 ImageBuffer 实例:
Bitmap^ MyClass::GetBitmapImageDestination(uchar *imageBytes, int imageWidth, int imageHeight, ColorMode colorMode) {
int channels = colorMode == ColorMode::Gray8 ? 1 : 4;
ComPtr<ImageBuffer> imageBuffer;
MakeAndInitialize<ImageBuffer>(&imageBuffer, imageWidth * imageHeight * channels, imageBytes);
auto iinspectable = (IInspectable*)reinterpret_cast<IInspectable*>(imageBuffer.Get());
IBuffer^ byteBuffer = reinterpret_cast<IBuffer^>(iinspectable);
return ref new Bitmap(Windows::Foundation::Size((float)imageWidth, (float)imageHeight), colorMode, (uint)(imageWidth * channels), byteBuffer);
}
希望这对某人有帮助!