How to upload imagick resource to media in wordpress?

 $filePath = wp_get_attachment_url( $id );
$tempfilename = explode("/", $filePath);
$temppdffile = end($tempfilename);
$cuurentPath = plugin_dir_path( __FILE__ ).$temppdffile;
$im = new Imagick();
$im->setResolution(300, 300);
$im->readImage( $cuurentPath.'[0]'); 
$im->setImageFormat('jpg');

I have above code.. i have successsfully generated image.. $im But i have to save image to.. media in wordpress as a featured image ? Any idea.. tried every thing

$filePath = wp_get_attachment_url( $uploaded);

$tempfilename = explode("/", $filePath);
$temppdffile = end($tempfilename);
$thumb = basename($temppdffile, ".pdf");
$cuurentPath = get_attached_file( $uploaded );
echo "current path ",$cuurentPath."</br>";
$thumbDirectory = plugin_dir_path( __FILE__ );
$im = new Imagick();
$im->setResolution(300, 300);
$im->readImage( $cuurentPath.'[0]'); 
$im->setImageFormat('jpg');
$r = "featured".rand(5, 200000).'_fea.jpg';
echo $r;
$newFileName = $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/pdftohtml/pdfimage/';
$myfile = file_put_contents($newFileName.$r, $im , FILE_APPEND | LOCK_EX);
//$myfile = $im->writeImage($newFileName.$r);
//$myfile = $im->writeImageFile($newFileName.$r);
//$fh = fopen($newFileName.$r, (file_exists($newFileName.$r)) ? 'a' : 'w');
//fwrite($fh, $im);
//fclose($fh);
//var_dump($myfile);
//done image add
$n =  _uploadImageToMediaLibrary($post_lesson,plugins_url()."/pdftohtml/pdfimage/".$r);
$s = media_sideload_image(plugins_url()."/pdftohtml/pdfimage/".$thumb,$post_lesson);
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_lesson, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if(sizeof($attachments) > 0){
                                // set image as the post thumbnail
                                set_post_thumbnail($post_lesson, $attachments[0]->ID);
                            }
echo "Story Successfully uploaded";


}
function _uploadImageToMediaLibrary($postID, $url, $alt = "blabla") {

   /* require_once("../sites/$this->_wpFolder/wp-load.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/image.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/file.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/media.php"); */
    //echo $url;

    $tmp = download_url( $url );
    $desc = $alt;
    $file_array = array();

    // Set variables for storage
    // fix file filename for query strings
    preg_match('/[^/?]+/.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
    $file_array['name'] = basename($matches[0]);
    $file_array['tmp_name'] = $tmp;

    // If error storing temporarily, unlink
    if ( is_wp_error( $tmp ) ) {
        @unlink($file_array['tmp_name']);
        $file_array['tmp_name'] = '';
    }

Thankfully i solved my self.. you know the problem is .. I missed directory separator “/” in $_SERVER