Using Nativescript + Angular, we are developing a mobile application that allows users to take photos then upload the photos to server. This application has specific requirement on the aspect ratio of the photos so we are trying to use the crop() API in nativescript-bitmap-factory plugin (part of nativescript-toolbox) to crop the photo after it is captured. This worked fine on Android but failed on iOS with this error: Unhandled Promise rejection: The method ImageSource.setNativeSource() expects UIImage instance. Here is the code snippet:
import * as BitmapFactory from "nativescript-bitmap-factory";
public cropImage(image : ImageSource) : ImageSource {
let mutable = BitmapFactory.makeMutable(image);
return BitmapFactory.asBitmap(mutable).dispose((bmp) => {
let croppedImage = bmp.crop({x:10,y:10}, {width:300,height:300});
console.log("Image cropped!")
return croppedImage.toImageSource();
});
}
The error was thrown in the last line
croppedImage.toImageSource();
I examined the nativescript-bitmap-factory code and realized that the crop() API returns an instance of CGImage (instead of UIImage expected by the ImageSource). According to this article https://medium.com/@ranleung/uiimage-vs-ciimage-vs-cgimage-3db9d8b83d94, it is fairly straightforward to convert a CGImage to UIImage in objective-c. I have been struggling for a few days now trying to figure out how to convert a CGImage to UIImage in Nativescript realm. I filed a bug against the nativescript-toolbox (see https://github.com/mkloubert/nativescript-toolbox/issues/10) a couple of weeks ago but there was no response. Can Nativescript experts out there share some thoughts or pointers on how this can be done? Is it reasonable to request Nativescript ImageSource be enhanced to support CGImage as well?
You could use the native method to convert CGImage
into UIImage
let mutable = BitmapFactory.makeMutable(image);
return BitmapFactory.asBitmap(mutable).dispose((bmp) => {
let croppedImage = bmp.crop({ x: 10, y: 10 }, { width: 300, height: 300 });
return isAndroid ? croppedImage.toImageSource() :
fromNativeSource(UIImage.alloc().initWithCGImage(croppedImage.nativeObject));
});