Wednesday, May 29, 2013

Upload ảnh bị lỗi ra ảnh đen xì, chán !

Vừa chế tạo xong cái code upload và xén ảnh cho đẹp, thì lại mắc phải cái lỗi toi mạng đó là trả về ảnh đen khi upload PNG, không hiểu tí nào lun, trước đây nó chạy tốt lắm :D


$valid = false;
    #var_dump( $_FILES);
# nếu file nhỏ hơn 6Mb | 6291456
# phần này tự resize để tránh hack và tiết kiệm băng thông
# Lưu ý : con shell thông thường không có điểm ảnh

# không cho nó up ảnh lằng nhằng @

$size = filesize($_FILES['file']['tmp_name']);
$file_upload = $_FILES["file"]["tmp_name"];

if ($size > MAX_SIZE || $size < 10)    {
    $valid = false;
    //    exit('Size ảnh quá lớn ... hoặc quá nhỏ ...');
}

if ($_FILES["file"]["error"] == 1)
    exit('Xảy ra lỗi gì đó của server, bạn thử lại ...');

if ( ! $file_upload )
    exit('Không có file nào được chọn ...');

$valid_mime_types = array(
    "image/gif",
    "image/png",
    "image/jpeg",
    "image/pjpeg",
);
$valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
// Check that the uploaded file is actually an image
// and move it to the right folder if is.
if (in_array($_FILES["file"]["type"], $valid_mime_types)) {
    $valid = true;
}


$file_extension = strrchr($_FILES["file"]["name"], ".");

// Check that the uploaded file is actually an image
// and move it to the right folder if is.
if (in_array($file_extension, $valid_file_extensions)) {
    $valid = true;
}
if (@getimagesize($_FILES["file"]["tmp_name"]) !== false) {
    $valid = true;
}

#
#    Function resize chúng nó đi ... cho bé lại ... keke !
#
function jam_img_resize($target, $newcopy, $w, $h, $ext) {
    list($w_orig, $h_orig) = getimagesize($target);
    $scale_ratio = $w_orig / $h_orig;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;
    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    if ($ext == "gif"){
    $img = imagecreatefromgif($target);
    } else if($ext =="png"){
    $img = imagecreatefrompng($target);
    } else {
    $img = imagecreatefromjpeg($target);
    }
    $tci = imagecreatetruecolor($w, $h);
    // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);

    imagejpeg($tci, $newcopy, 84);
    // free memory
    imagedestroy($tci);
   
    return $newcopy;
}

    // kiểm tra nào ...
    // nếu hợp lệ
    if ( $valid ) {
        #jam_img_resize($target, $newcopy, $w, $h, $ext);
        $return = jam_img_resize($file_upload , HOST_MEDIA . 'small-' . FILE_NAME . $file_extension, 80, 80, $file_extension);
        jam_img_resize($file_upload , HOST_MEDIA .  FILE_NAME . $file_extension, 300, 296, $file_extension);
        echo $return;
        #unlink($file_upload);
    }

Bạn nào có kinh nghiệp chỉ cái , cứ up PNG mới bị ...

No comments:

Post a Comment