Viewed   95 times

I need to save an image from a url using CURL and save it to a folder on my server. I've been battling with this code to no avail. Ideally I'd like to grab the image and save it as "photo1" or something. Help!

    function GetImageFromUrl($link)

    {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_POST, 0);

    curl_setopt($ch,CURLOPT_URL,$link);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result=curl_exec($ch);

    curl_close($ch);

    return $result;

    }

    $sourcecode = GetImageFromUrl($iticon);

    $savefile = fopen(' /img/uploads/' . $iconfilename, 'w');
    fwrite($savefile, $sourcecode);
    fclose($savefile);

 Answers

2

try this:

function grab_image($url,$saveto){
    $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);
    if(file_exists($saveto)){
        unlink($saveto);
    }
    $fp = fopen($saveto,'x');
    fwrite($fp, $raw);
    fclose($fp);
}

and ensure that in php.ini allow_url_fopen is enable

Monday, August 8, 2022
4

This was pretty confusing, because it sounded like you were only interested in saving one image per page. But then the code makes it look like you're actually trying to save every image on each page. So it's entirely possible I completely misunderstood... But here goes.

Looping over each page isn't that difficult:

$i = 1;
$l = 101;

while ($i < $l) {
    $html = get_data('http://somedomain.com/id/'.$i.'/');
    getImages($html);
    $i += 1;
}

The following then assumes that you're trying to save all the images on that particular page:

function getImages($html) {
    $matches = array();
    $regex = '~http://somedomain.com/images/(.*?).jpg~i';
    preg_match_all($regex, $html, $matches);
    foreach ($matches[1] as $img) {
        saveImg($img);
    }
}

function saveImg($name) {
    $url = 'http://somedomain.com/images/'.$name.'.jpg';
    $data = get_data($url);
    file_put_contents('photos/'.$name.'.jpg', $data);
}
Thursday, November 3, 2022
 
ems305
 
5

Image resizer class class

class Process{
    // List of supported image formats.     
    private $valid_ext = array( 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'wbmp' );

    // Whether or not that script should continue
    private $halt = false;

    // Image Configuration array and Source Image
    public $errmsg = "";
    var $image = array();
    var $s_image;

    public function render($source){        
        $this->s_image = $source;  
        //set the image to this class attr for other to be accessible
        //list the image height and width
        list($this->image['width'], $this->image['height']) = getimagesize($source);  

        //get the image extension       
        $this->image['extension'] = strtolower(preg_replace('/^.*.([^.]+)$/D', '$1', $this->s_image));
        if (!(in_array( $this->image['extension'], $this->valid_ext))){         
            $this->errmsg = "invalid format";
            $this->halt = true; 
            return false;  //terminate the function if type format is not correct
        }

        //i think mime type should be checked instead of extension 
        //well in that case i will do sometime  

        //create image
        switch($this->image['extension']){
            case 'png';
                $this->image['render'] = imagecreatefrompng( $this->s_image );
                    imagealphablending( $this->image['render'], false );
                    imagesavealpha( $this->image['render'], true );
                break;
            case 'jpg';
                    $this->image['render'] = imagecreatefromjpeg( $this->s_image );
                break;
            case 'jpeg';
                    $this->image['render'] = imagecreatefromjpeg( $this->s_image );
                break;
            case 'gif';
                    $this->image['render'] = imagecreatefromgif( $this->s_image );
                break;
            case 'bmp';
                    $this->image['render'] = imagecreatefromwbmp( $this->s_image );
                break;
            case 'wbmp';
                    $this->image['render'] = imagecreatefromwbmp( $this->s_image );
                break;
            default: 
                    $this->errmsg = "invalid format";
                    $this->halt = true;
                return false;
                break;
        }       
    }

    public function contrain($width, $height){      
        if(!($this->halt)){
            if($this->image['extension'] == 'gif'){
                        $this->image['composite'] = imagecreatetruecolor($width, $height);
                        imagecopyresample($this->image['composite'], $this->image['render'], 0, 0, 0, 0,
                                $width, $height, $this->image['width'], $this->image['height'] );

                        $this->image['colorcount'] = imagecolorstotal( $this->image['render'] );

                        imagetruecolortopalette( $this->image['composite'], true, $this->image['colorcount'] );

                        imagepalettecopy( $this->image['composite'], $this->image['render'] );

                        $this->image['transparentcolor'] = imagecolortransparent( $this->image['render'] );

                        imagefill( $this->image['composite'], 0, 0, $this->image['transparentcolor'] );

                        imagecolortransparent( $this->image['composite'], $this->image['transparentcolor'] );
            } else {

                        $this->image['composite'] = imagecreatetruecolor($width, $height);

                        imagecopyresampled( $this->image['composite'], $this->image['render'], 0, 0, 0, 0, 
                            $width, $height, $this->image['width'], $this->image['height'] );
            }
        }else{
            $this->halt = true;
            $this->errmsg = "Execution halted";
            return false;
        }
    }

    public function proportion($max_width, $max_height){        
        if (!( $this->halt)){

            if($this->image['extension'] == 'gif'){

                $this->image['ratio'] = ( $this->image['width'] > $this->image['height'] ) ? $max_width / $this->image['width'] : $max_height/$this->image['height'];

                if( $this->image['width'] > $max_width || $this->image['height'] > $max_height ) { 
                    $new_width = $this->image['width'] * $this->image['ratio']; 
                    $new_height = $this->image['height'] * $this->image['ratio']; 
                }else{
                    $new_width = $this->image['width']; 
                    $new_height = $this->image['height'];
                }

                $this->image['composite'] = imagecreatetruecolor( $new_width, $new_height );

                imagecopyresampled( $this->image['composite'], $this->image['render'], 0, 0, 0, 0, $new_width, $new_height, $this->image['width'], $this->image['height'] );

                $this->image['colorcount'] = imagecolorstotal( $this->image['render'] );

                imagetruecolortopalette( $this->image['composite'], true, $this->image['colorcount'] );

                imagepalettecopy( $this->image['composite'], $this->image['render'] );

                $this->image['transparentcolor'] = imagecolortransparent( $this->image['render'] );

                imagefill( $this->image['composite'], 0, 0, $this->image['transparentcolor'] );

                imagecolortransparent( $this->image['composite'], $this->image['transparentcolor'] );

            }else{
                $this->image['ratio'] = ( $this->image['width'] > $this->image['height'] ) ? $max_width / $this->image['width'] : $max_height/$this->image['height']; 

                if( $this->image['width'] > $max_width || $this->image['height'] > $max_height ) { 

                    $new_width = $this->image['width'] * $this->image['ratio']; 

                    $new_height = $this->image['height'] * $this->image['ratio']; 
                }else{
                    $new_width = $this->image['width']; 

                    $new_height = $this->image['height'];
                } 

                $this->image['composite'] = imagecreatetruecolor( $new_width, $new_height );

                imagecopyresampled( $this->image['composite'], $this->image['render'], 0, 0, 0, 0, $new_width, $new_height, $this->image['width'], $this->image['height'] );
            }
        } else {
                $this->errmsg = "Execution halted";
            $this->halt = true;
            return false;
        }       
    }

    public function output($quality = 100){     
        if(!(is_numeric($quality))){
            $quality = 100;
        }
        if(!($this->halt)){
            switch($this->image['extension']){
            case 'png';
                header('Content-Type: image/png');
                imagepng($this->image['composite'], null, null );
                break;
            case 'jpg';
                header('Content-Type: image/jpeg');
                imagejpeg($this->image['composite'], null, $quality);
                break;
            case 'jpeg';
                header( 'Content-Type: image/jpeg' );
                imagejpeg($this->image['composite'], null, $quality);
                break;
            case 'gif';
                header( 'Content-Type: image/gif' );
                imagegif($this->image['composite'], null, $quality);
                break;
            case 'bmp';
                header('Content-Type: image/wbmp' );
                imagewbmp($this->image['composite'], null, null);
                break;
            case 'wbmp';
                header('Content-Type: image/wbmp' );
                imagewbmp($this->image['composite'], null, null);
                break;
            default: 
                $this->errmsg = "invalid format";
                return false;
                break;
            }
        }else{
            $this->errmsg = "Execution halted";
            return false;
        }
    }

    public function saveto($destination, $filename, $quality = 100){        
        if(!(is_numeric($quality))){
            $quality = 100;
        }
        if(!($this->halt)){
            switch($this->image['extension']){
            case 'png';
                imagepng($this->image['composite'],  $destination.DIRECTORY_SEPARATOR.$filename, null);
                break;
            case 'jpg';
                imagejpeg($this->image['composite'], $destination.DIRECTORY_SEPARATOR.$filename, $quality );
                break;
            case 'jpeg';
                imagejpeg($this->image['composite'], $destination.DIRECTORY_SEPARATOR.$filename, $quality );
                break;
            case 'gif';
                imagegif($this->image['composite'],  $destination.DIRECTORY_SEPARATOR.$filename, $quality );
                break;
            case 'bmp';
                imagewbmp($this->image['composite'], $destination.DIRECTORY_SEPARATOR.$filename, null);
                break;
            case 'wbmp';
                imagewbmp($this->image['composite'], $destination.DIRECTORY_SEPARATOR.$filename, null);
                break;
            default: 
                $this->errmsg = "invalid format";
                return false;
                break;
            }
        }else{
            $this->errmsg = "Execution halted";
            return false;
        }
    }

    public function clear_cache(){
        imagedestroy( $this->image['composite'] );
        imagedestroy( $this->image['render'] );
        unset($this->image);
        unset($this->s_image);
        $this->halt = false;
    }
}

And usage

$process = new Process();

$process->render($filepath);

$process->proportion($width, $height);

$process->saveto($upload_path, $filename, $quality); //$quality is in %
Saturday, August 6, 2022
 
1

I had to do this recently myself.

First I put my canvasData into a hidden field and posted it to my PHP page.

It comes back in this format: data:image/png;base64,iVBORw0......

You need to split the data up first, as this: data:image/png;base64, is header information. The rest is the encoded data.

$rawData = $_POST['imageData'];
$filteredData = explode(',', $rawData);

$unencoded = base64_decode($filteredData[1]);

I then create the image on my server:

//Create the image 
$fp = fopen('sigs/test1.png', 'w');
fwrite($fp, $unencoded);
fclose($fp); 

And then read it to do whatever I want with it.

$file_name = 'test1.png';
$file_size = strlen($filteredData[1])/1024; //This may be wrong, doesn't seem to break for me though.


$fh = fopen('sigs/test1.png', 'r');
$content = fread($fh, $file_size);
$content = base64_encode($content);
fclose($fh);

I'm more than sure there is a much more elegant solution to this, but this has been working for me!

Check this for more info (possibly): My own question

Monday, September 12, 2022
4

It is not recommended to store your entire image as a blob in your sqlite database. Instead download it to a certain location in sd and save that path in a column in your sqlite db. Also, there is a bug in the android Cursor class that will not handle correctly the images that are bigger in size than 1MB. See here. To download image from an AsyncTask you can use something like this:

public class MainActivity extends Activity {
    protected SQLiteDatabase sqlitedatabase_obj;
    DataBaseHelper databasehlpr_obj;
    int accId;
    byte[] accImage;

    byte[] logoImage;
    byte[] photo;@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AndroidContext.setContext(this);
    sqlitedatabase_obj = DataBaseHelper.getInstance().getDb();
    new ImageDownloader().execute("http://images.100bestbuy.com/images/small_137385013870957.jpg");


}

private byte[] getLogoImage(String url) {
    try {
    URL imageUrl = new URL(url);
    URLConnection ucon = imageUrl.openConnection();
    System.out.println("11111");
    InputStream is = ucon.getInputStream();
    System.out.println("12121");

    BufferedInputStream bis = new BufferedInputStream(is);
    System.out.println("22222");

    ByteArrayBuffer baf = new ByteArrayBuffer(500);
    int current = 0;
    System.out.println("23333");

    while ((current = bis.read()) != -1) {
        baf.append((byte) current);

    }
    photo = baf.toByteArray();
    System.out.println("photo length" + photo);


} catch (Exception e) {
    Log.d("ImageManager", "Error: " + e.toString());
}
return accImage;
}
public void insertUser() {
    ContentValues userdetailValues = new ContentValues();
    userdetailValues.put("account_image", photo);
    sqlitedatabase_obj.insert(DataBaseHelper.IMG_table, null, userdetailValues);
}

private class ImageDownloader extends AsyncTask<String, Void, Void> {

    private ProgressDialog progressDialog;

    @Override
    protected Void doInBackground(String... param) {

         sqlitedatabase_obj.delete(DataBaseHelper.IMG_table, null, null);
         logoImage = getLogoImage(param[0]);

         insertUser();
    }

    @Override
    protected void onPreExecute() {

        progressDialog = ProgressDialog.show(MainActivity.this,
                "Wait", "Downloading Image");

    }

    @Override
    protected void onPostExecute(Void result) {
        progressDialog.dismiss();

    }

}

}
Wednesday, August 3, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :