簡體   English   中英

從字符串中提取 base64 圖像並用表單發布

[英]Extract base64 image from string and post it with form

我正在嘗試在我的Laravel項目中使用我的表單上傳圖像。 我有一個圖像裁剪器,可以將圖像保存為data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/..

裁剪器發送一個JSON字符串,其中包含文件的base64編碼字符串,我需要將JSON字符串解析為一個對象,然后提取base64字符串並將其轉換為文件對象。

我正在使用Image Intervention進行上傳過程

控制器功能

public function store(Request $request)

    {

        // save post in db

        $post = new Post;

        $post->title = $request->title;
        $post->body = $request->body;
        $post->user_id = auth()->id();



        if ($request->hasFile('featimage')) {
            $image = $request->file('featimage');
            $filename = time() . '.' . $image->getCLientOriginalExtension();

            $image = trim($image);
            $image = str_replace('data:image/png;base64,', '', $image);
            $image = str_replace('data:image/jpg;base64,', '', $image);
            $image = str_replace('data:image/jpeg;base64,', '', $image);
            $image = str_replace('data:image/gif;base64,', '', $image);
            $image = str_replace(' ', '+', $image);

            $imagedata = base64_decode($image);
            //Set image whole path here 

            $location = public_path('images/uploads/' . $filename);
            Image::make($image)->save($location);
            $post->image = $filename;
        }

        $post->save();

        $post->tags()->sync($request->tags, false);


        Session::flash('success', 'The blog post was saved successfully!');

        return redirect()->route('posts.show', $post->id);

                    }

看法

<form class="form-horizontal" action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">{{ csrf_field() }}

<fieldset class="form-group">
<label for="featimage">Upload Image</label>
<input type="file" class="form-control slim" data-ratio="4:3" name="featimage">

<label class="col-md-2 col-form-label">Post Body</label>
<textarea type="textarea" class="form-control" rows="10" name="body"></textarea>
</fieldset>

<button class="btn btn-primary btn-block" name="submit">Save</button>
<button class="btn btn-danger btn-block" name="submit">Cancel</button>

</form>    

我讀過其他類似的帖子,我顯然遺漏了一些東西,但我不知道是什么。

你可以試試這個功能。

    function uploadImage($base_64_string,$image_name)
{

    preg_match("/^data:image\/(.*);base64/i", $base_64_string, $match);
    $extension_array = explode('/', (explode(';', $base_64_string))[0]);
    $extension = end($extension_array);

    $img = $base_64_string;
    if ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg'){
        $img = str_replace('data:image/' . $extension . ';base64,', '', $img);}
    elseif ($extension == 'mp4' || $extension == 'mov'){
        $img = str_replace('data:video/' . $extension . ';base64,', '', $img);
    }
    $img = str_replace(' ', '+', $img);

    $data = base64_decode($img);

    $fileNameI = $image_name.'_'.rand().time() . '.' . $extension;

//Uploading Image To S3 Bucket
    $s3 = Storage::disk('s3-image');
    $filePath = Config::get('common.Image_Folder') . $fileNameI;
    $s3->put($filePath, $data, 'public');

    return $fileNameI;
}

如果您沒有 Bucket,則可以將圖像存儲在本地目錄中。

試試這個希望它對你有用。

$featimage = $request->featimage; // base64 encoded image string

if (!empty($featimage)) {
    $image_parts = explode(";base64,", $featimage);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $imagename = rand(1, 999) . time() . '.png';
    $RootPath = public_path("images/uploads/"); // path where you want to upload image
    if (!File::exists($categoryRootPath)) {
        File::makeDirectory($categoryRootPath, 0777, true, true);
    }

    file_put_contents($RootPath . $imagename, $image_base64);

    $post->image = $imagename;  
}

我在我的程序中運行了你的代碼,但出現了很多錯誤。 如果您嘗試將輸入作為 base64 編碼字符串作為'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/..'並將其轉換為圖像文件,請使用以下代碼:

$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = auth()->id();

if ($request->featimage) {
    $image = $request->featimage; // your base64 encoded
    $filename = time() . '.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];

    $image = str_replace('data:image/jpg;base64,', '', $image);
    $image = str_replace(' ', '+', $image);
    $location = public_path('images/uploads/' . $filename);
    Image::make($image)->save($location);
    $post->image = $filename;
}

$post->save();

如果您嘗試獲取普通圖像文件並將其保存在公共文件夾中並將其轉換為 base64 格式,請使用以下代碼。

$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = auth()->id();

if ($request->hasFile('featimage')) {
    $image = $request->file('featimage'); 
    $extension = $image->getCLientOriginalExtension(); //gives extension of image
    $filename = time() . '.' . $extension; //gives filename

    $location = public_path('images/uploads/' . $filename); //sets path

    $image = Image::make($image)->save($location); //makes image and saves it to that location

    $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($image); //changes image to base64 image

    $post->image = $filename;
}

$post->save();

我希望以下代碼為您提供解決方案。 謝謝你。

暫無
暫無

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

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