0

我正在使用带有以下代码的函数将图像从 url 复制到我的 web 目录,但我不知道为什么有些图像没有 100% 复制。

这是我的网页目录中错误图像的副本http://www.aligatoor.pl/uploads/deals/2632b3802e8ed7abe83788dab605bbf7.jpg

这里是原始图像http://infobuzer.pl/img/r4d3k/voucher/50e35a84c9038.jpg

function upload_file($file_path)
{
    $deal_img_data=file_get_contents($file_path);

    $file_name=md5($file_path).".jpg";

    if(!file_exists($file_name))
    {
        $file=fopen($file_name,"w+");

        fwrite($file,$deal_img_data);
    }
}

我也尝试过使用 CURL,但它仍然无法正确复制一些图像。

卷曲代码:

$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
$saveto=md5($url).".jpg";
if(file_exists($saveto)){
    unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
4

4 回答 4

0

我不确切知道您的问题的原因是什么,但我在文件处理方面遇到了类似的问题,我使用这种方法解决了它:

  if( $handle =fopen($filename, "wb+") ){
    if(flock($handle, LOCK_EX))
    {
      fseek($handle, 0); 
      ftruncate($handle, 0); 

      fwrite($handle, $newcontent);

      fflush($handle); 
      flock($handle, LOCK_UN); 
    }
    fclose($handle); 
  }

群()

编辑:为了处理图像,最好使用imagejpeg()imagecreatefromjpeg()等图像函数,以获得更好的安全性和准确的结果。

例子:

  $im = @imagecreatefromjpeg($image);
  if(is_bool($im)){
   die("Invalid Image detected!");
  }
  else{

    if(!imagejpeg($im, $newpath)){
     die("Image not saved!");
    }
    else{
     die("Image saved!");
    }  
  }

Edit2:添加这个而不是使用 file_get_contents()

<?php

$handle = fopen($file_path, "rb");
$deal_img_data = stream_get_contents($handle);
fclose($handle);

?> 
于 2013-02-14T21:44:13.623 回答
0

你的功能工作正常

只需删除旧图像并尝试重新下载即可。

还添加:

fclose($file);
于 2013-02-14T21:41:28.400 回答
0

我找到了方法,所以如果有人和我有类似的问题,他可以尝试使用这个功能:

function grab_image($url){
    $ch = curl_init ($url);
    $saveto = md5($url).".jpg";
    $fp = fopen($saveto,'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}
于 2013-02-15T00:05:50.877 回答
-2

尝试在函数开头添加 set_time_limit(0)

于 2013-02-14T21:42:11.060 回答