簡體   English   中英

在Laravel API中從React-Native應用調整Base64圖像的大小?

[英]Resizing a base64 image from react-native app in laravel api?

我正在嘗試開發一個應用程序,該應用程序可以從他們的設備攝像頭以base64發送用戶圖像輸入,並讓我的api處理,調整圖像大小並將其保存為jpg格式,我使用react-native image-picker作為攝像頭處理程序。 到目前為止,這是我的代碼

// 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));
 }

這是對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
        });
      }
    });
 };

它顯示Unable to init from binary data為錯誤,我該怎么做? 任何幫助將不勝感激...

您似乎正在使用Intervention Image軟件包。 文檔顯示,確實有可能將base64字符串轉換為Image

我不清楚的是為什么要從編碼的圖像中刪除初始字符串data:image/png;base64, 我可以想象這對干預工作是必要的。

我縮短並重寫了您的代碼。 這對我有用:

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');

為了便於測試,可以使用以下base64圖像(它表示單個黑色像素):

$selfie = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';

如果您想進行一些深入的調試,請查看Intervention的AbstractDecoder類及其init()函數。 這是識別圖像類型的地方,由於某種原因,圖像被識別為二​​進制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM