使用Symfony和VichUploader将base64图像转换为图像文件 [英] base64 image to image file with Symfony and VichUploader

查看:159
本文介绍了使用Symfony和VichUploader将base64图像转换为图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在symfony中,我有一个实体Program,其属性为image.使用VichUploaderBundle完成图像的上传,命名和将其放置在正确的目录中.实体看起来像这样:

In symfony, I have an entity Program, which has the attribute image. Uploading images, naming them and putting them in the right directory is done with the VichUploaderBundle. The entity looks like this:

//...

/**
 * NOTE: This is not a mapped field of entity metadata, just a simple property.
 *
 * @Assert\Image(
 *     maxSize="5M",
 *     mimeTypesMessage="The file you tried to upload is not a recognized image file"
 *    )
 * @Vich\UploadableField(mapping="program_image", fileNameProperty="imageName")
 *
 * @var File
 */
private $image;

/**
 * @ORM\Column(type="string", length=191, nullable=true)
 */
private $imageName; 

//...

现在,我希望在上载图像之前对其进行处理,这是我使用一些返回base64字符串的JS完成的.我将此字符串放在一个隐藏的输入字段base64Image中.然后,我在控制器中检索此字符串,并尝试将其转换为图像,可以像这样保存到我的实体中:

Now I wish for images to be processed before they are uploaded, which I have done with some JS that returns a base64 string. I put this string in a hidden input field, base64Image. I then retrieve this string in my controller and try to make it into an image that I can save to my entity like so:

if ($form->isSubmitted() && $form->isValid()) {
    $program = $form->getData();

    $base64String = $request->request->get('base64Image');
    $decodedImageString = base64_decode($base64String);

    $program->setImage($decodedImageString);

//etc.....

程序在最后一行出现. $decodedImageString实际上是另一个需要首先创建到文件中的字符串.我调查了file_put_contents以描述者的身份在此处创建文件,但没有运气.

The program occurs with the last line. $decodedImageString is actually another string that first needs to be created into a file. I have looked into file_put_contents to create a file as describer here, but with no luck.

文件名不能为空

The filename cannot be empty

是我收到的错误.另外,我也不知道这是否适用于VichUploaderBundle,也许这个问题的答案也已经过时了.关于我可以做什么的任何建议?

Is the error I receive. Also I don't know if this would work with the VichUploaderBundle and perhaps the answer in that question is also outdated. Any suggestions on what I could do?

修改: 使用以下代码进行了转换和上传:

Got the converting and uploading working with the following code:

define('UPLOAD_DIR', 'images/');
$img = $request->request->get('base64Image');
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpeg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

现在,我只需要以某种方式加载VichUploaderBundle配置,或者也许根本不使用它.

Now I just need to load the VichUploaderBundle config somehow, or maybe not use that altogether perhaps.

推荐答案

一种解决方案是首先将base64文件转换为symfony uploadFile.

An attempt of solution is to transform first the base64 file into a symfony uploadedFile.

  • 您定义此服务
<?php

    namespace App\Utils;

    use Symfony\Component\HttpFoundation\File\UploadedFile;

    class UploadedBase64File extends UploadedFile
    {

        public function __construct(string $base64String, string $originalName)
        {
            $filePath = tempnam(sys_get_temp_dir(), 'UploadedFile');
            $data = base64_decode($base64String);
            file_put_contents($filePath, $data);
            $error = null;
            $mimeType = null;
            $test = true;

            parent::__construct($filePath, $originalName, $mimeType, $error, $test);
        }

    }

然后这是另一个服务,用于提取pur base64字符串图像

And then this another service to extract the pur base64 string image

<?php

    namespace App\Utils;

    class Base64FileExtractor    
    {

        public function extractBase64String(string $base64Content)
        {

            $data = explode( ';base64,', $base64Content);
            return $data[1];

        }

    }

  • 在您的控制器中,您可以执行以下操作:
  •     <?php
    
        namespace App\Controller\Api;
    
        use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
        use Symfony\Component\HttpFoundation\Request;
        use Symfony\Component\Routing\Annotation\Route;
        use App\Utils\UploadedBase64File;
        use App\Utils\Base64FileExtractor;
    
        class CoreController extends AbstractController
        {
           /**
             * @Route("/images", methods={"POST"}, name="app_add_image")
             */
             public function addImage(Request $request, Base64FileExtractor $base64FileExtractor) 
             {
    
                 //...
    
                 if($form->isSubmitted() && $form->isValid()) {
    
                      $base64Image = $request->request->get('base64Image');
                      $base64Image = $base64FileExtractor->extractBase64String($base64Image);
                      $imageFile = new UploadedBase64File($base64Image, "blabla");
                      $program->setImage($imageFile);
    
                      //... 
                      // Do thing you want to do
                 }
                 // Do thing you want to do
    
             }
       }
    

    • 您的Program实体中的setImage方法可以类似于
    •        /**
               * @param null|File $image
               * @return Program
               */
              public function setImage(?File $image): Program
              {
                  $this->image = $image;
      
                  if($this->image instanceof UploadedFile) {
                      $this->updatedAt = new \DateTime('now');
                  }
      
                  return $this;
              }
      

      如果要验证图像,则应在处理表格后立即进行设置,并且验证将按习惯进行. 我希望这个想法能对您有所帮助.

      If you want to validate the image, you should set it directly after handling form and the validation will be done habitually. I hope this idea can help you.

      这篇关于使用Symfony和VichUploader将base64图像转换为图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆