当前位置: 首页 > 面试题库 >

PHP-获取base64 img字符串解码并另存为jpg(结果为空白图片)

姚鹤龄
2023-03-14
问题内容

嗨,我实际上是通过ajax将base64图像字符串通过ajax发送到php脚本,该脚本仅解码字符串并将内容另存为.jpg文件。

但是结果是空白图像。

这怎么可能?

php脚本

$uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
            foreach ($uploadedPhotos as $file) {
                if($this->input->post('photo_1')){
                     $photoTemp = base64_decode($this->input->post('photo_1'));


                    /*Set name of the photo for show in the form*/
                    $this->session->set_userdata('upload_'.$file,'ant');
                    /*set time of the upload*/
                    if(!$this->session->userdata('uploading_on_datetime')){
                     $this->session->set_userdata('uploading_on_datetime',time());
                    }
                     $datetime_upload = $this->session->userdata('uploading_on_datetime',true);
                    /*create temp dir with time and user id*/
                    $new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
                    @mkdir($new_dir);
                    /*move uploaded file with new name*/
                    @file_put_contents( $new_dir.$file.'.jpg',$photoTemp);


            }

对于ajax来说可以,因为echo $ photoTemp返回字符串。

我尝试过var_dump(@file_put_contents( $new_dir.$file.'.jpg',$photoTemp));并且它返回,bool(true)因为保存了图像,但是图像中没有内容:(空图像

对于空图像,我的意思是说,文件已创建并命名,并且它具有与传递给php的内容相同的大小,但是当我尝试打开该图像进行预览时,它说,由于损坏或文件损坏而无法打开文件类型格式

无论如何,这是将照片作为base64并将其发送到php的JS:

<script type="text/javascript">

var _min_width = 470;
var _min_height = 330;
var _which;
var _fyle_type;
var  io;
var allowed_types = new Array('image/png','image/jpg','image/jpeg');
if (typeof(FileReader) === 'function'){
$('input[type="file"]').on('change', function(e) {
    var _file_name = $(this).val();
    $('.'+_which+'_holder').text(_file_name);
    var file = e.target.files[0];

    if (!in_array(file.type,allowed_types) || file.length === 0){
        notify("You must select a valid image file!",false,false); 
        return;
    }

    if(file.size > 3145728 /*3MB*/){
        notify("<?php echo lang('each-photo-1MB'); ?>",false,false); 
        return;
    }
    notify_destroy();

    var reader = new FileReader();
    reader.onload = fileOnload;
  reader.readAsDataURL(file);


});

function fileOnload(e) {
    var img = document.createElement('img');
    img.src = e.target.result;

    img.addEventListener('load', function() {
        if(img.width < _min_width || img.height < _min_height ){
        notify("<?php echo lang('each-photo-1MB'); ?>",false,false); 
        return;
        }


        $.ajax({
            type:'post',
            dataType:'script',
            data:{photo_1:e.target.result},
            url:_config_base_url+'/upload/upload_photos',
            progress:function(e){
                console.log(e);
            },
            success:function(d){
                $('body').append('<img src="'+d+'"/>');
            }
         });


    });

}
}
</script>

问题答案:

AFAIK,您必须使用图像函数imagecreatefromstring,imagejpeg创建图像。

$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

希望这会有所帮助。

PHP CODE WITH IMAGE DATA

$imageDataEncoded = base64_encode(file_get_contents('sample.png'));
$imageData = base64_decode($imageDataEncoded);
$source = imagecreatefromstring($imageData);
$angle = 90;
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageName = "hello1.png";
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

因此,以下是程序的php部分.. NOTE带注释的更改Change is here

    $uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
     foreach ($uploadedPhotos as $file) {
      if($this->input->post($file)){                   
         $imageData = base64_decode($this->input->post($file)); // <-- **Change is here for variable name only**
         $photo = imagecreatefromstring($imageData); // <-- **Change is here**

        /* Set name of the photo for show in the form */
        $this->session->set_userdata('upload_'.$file,'ant');
        /*set time of the upload*/
        if(!$this->session->userdata('uploading_on_datetime')){
         $this->session->set_userdata('uploading_on_datetime',time());
        }
         $datetime_upload = $this->session->userdata('uploading_on_datetime',true);

        /* create temp dir with time and user id */
        $new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
        if(!is_dir($new_dir)){
        @mkdir($new_dir);
        }
        /* move uploaded file with new name */
        // @file_put_contents( $new_dir.$file.'.jpg',imagejpeg($photo));
        imagejpeg($photo,$new_dir.$file.'.jpg',100); // <-- **Change is here**

      }
    }


 类似资料:
  • 本文向大家介绍php解析http获取的json字符串变量总是空白null,包括了php解析http获取的json字符串变量总是空白null的使用技巧和注意事项,需要的朋友参考一下 今天同事项目中遇到一个问题,通过http接口获取的json字符串使用json_decode始终无法正确解析,返回空白。 直接把结果字符串复制出来手动创建一个变量却正常,在前端js也能解析,搞了半天不得其解,借助强大的谷歌

  • 我有以下结构: 我试图用len(event.Identificator)获得标识符的长度,但是我得到了len的无效参数 在给伦打电话之前,我先检查一下是不是零。我来自Java/C#/PHP背景,这是我第一次用GO写东西。

  • 我已经用Python创建了几个绘图,并试图将它们另存为。png文件或PDF。输入数据后,我将使用以下代码创建: 情节也很精彩。然而,每当我使用 plt.savefigSersic_Voids.png 为了保存,它这样做,文件显示在我的电脑上。对于我使用的每次和文件类型,文档都是空白的,没有绘图、轴或任何东西。 编辑1:我已经在使用要保存的格式,但运气不好。我没有plt。show()函数,每个Jup

  • 问题内容: 我将 图片获取 为base64字符串( ) ,下面是将转换为图片的函数, 现在,如果图像为png,则png库将创建图像,而jpg库将引发错误,反之亦然。 问题是当我上传png时效果很好,但是当我 上传jpg文件时 返回此错误 无效的JPEG格式:缺少SOI标记 输入为: 这可能有帮助 问题答案: 您将您的传递给,这开始消耗阅读器,只是发现输入不是有效的PNG,因此返回错误。 然后,将部

  • 如果我有这个字符串:“MyStringToForSpl的”,我想用这个词“环”来拆分它。如果我这样做:我将得到包含以下元素的数组: MyS 用于拆分 我无法找到拆分它并在结果数组中包含“ring”的最佳方法,如下所示: 1.我的 2 .戒指 3.ForSplitting