I'm trying to develop an app that can send a user image input in base64 from their device camera and let my api handle, resize and save the image in jpg format, I'm using react-native image-picker
as the camera handler. Here's my code so far
// in imageHandlerController.php
public function resizeImage($image) {
$resizeImage = Image::make($images)->resize(512, 512, function($constraint) {
$constraint->aspectRatio();
})->orientate();
return $resizeImage->response();
}
public function imageHandler(Request $request){
DB::beginTransaction();
try {
$constants = Config::get('constants');
$path = $constants['UPLOAD_PATH'].'/images';
$random_name = str_random(20);
$selfie = $request->selfieImage;
$selfie = str_replace('data:image/png;base64,', '', $selfie);
$selfie = str_replace(' ', '+', $selfie);
$selfie_name = 'selfie-'.$random_name.'.png';
File::put($path.'/partners/'.$selfie_name, $this->resizeImage($selfie));
}
Here's the post request on index.js
launchCameraSelfie = () => {
ImagePicker.showImagePicker(response => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
let source = response;
this.setState({
selfieImage: source.data
});
}
});
};
It show Unable to init from binary data
as an error How can i do this? any help will be appreciated...
It looks like you are using the Intervention Image
package. The documentation shows that it is indeed possible to convert a base64 string to an Image
.
What is unclear to me is why you remove the initial string data:image/png;base64,
from the encoded image. I can imagine this part to be necessary for Intervention to work.
I shortened and rewrote your code a bit. This works for me:
use Intervention\Image\ImageManagerStatic as Image;
$selfie = $request->selfieImage;
$img = Image::make($selfie);
$img->resize(512, 512, function($constraint) {
$constraint->aspectRatio();
})->orientate();
$img->save(storage_path('images') . '/test.png');
For easy testing, the following base64 image can be used (it represents a single black pixel):
$selfie = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
If you want to do some in-depth debugging, have a look at Intervention's AbstractDecoder
class and its init()
function. It is the place where the image type is identified, and for some reason your image is identified as binary.