HTML5 拖拽上传图片实例
拖拽上传最重要的就是js部分的代码,它实现了70%的功能,另外30%仅仅是把图片信息提交到后台,然后做对应的处理,比如压缩啊,裁剪啊云云。所以先来看下js实现代码吧。
; ??echo json_encode($r); ??function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) { ????$quality = $quality ? $quality : 80; ????$image = imagecreatefromstring($source); ????if ($image) { ????????// Get dimensions ????????$w = imagesx($image); ????????$h = imagesy($image); ????????if (($width && $w > $width) || ($height && $h > $height)) { ????????????$ratio = $w / $h; ????????????if (($ratio >= 1 || $height == 0) && $width && !$crop) { ????????????????$new_height = $width / $ratio; ????????????????$new_width = $width; ????????????} elseif ($crop && $ratio <= ($width / $height)) { ????????????????$new_height = $width / $ratio; ????????????????$new_width = $width; ????????????} else { ????????????????$new_width = $height * $ratio; ????????????????$new_height = $height; ????????????} ????????} else { ????????????$new_width = $w; ????????????$new_height = $h; ????????} ????????$x_mid = $new_width * .5;? //horizontal middle ????????$y_mid = $new_height * .5; //vertical middle ????????// Resample ????????error_log('height: ' . $new_height . ' - width: ' . $new_width); ????????$new = imagecreatetruecolor(round($new_width), round($new_height)); ????????imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h); ????????// Crop ????????if ($crop) { ????????????$crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height); ????????????imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height); ????????????//($y_mid - ($height * .5)) ????????} ????????// Output ????????// Enable interlancing [for progressive JPEG] ????????imageinterlace($crop ? $crop : $new, true); ??????????$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION)); ????????if ($dext == '') { ????????????$dext = $ext; ????????????$destination .= '.' . $ext; ????????} ????????switch ($dext) { ????????????case 'jpeg': ????????????case 'jpg': ????????????????imagejpeg($crop ? $crop : $new, $destination, $quality); ????????????????break; ????????????case 'png': ????????????????$pngQuality = ($quality - 100) / 11.111111; ????????????????$pngQuality = round(abs($pngQuality)); ????????????????imagepng($crop ? $crop : $new, $destination, $pngQuality); ????????????????break; ????????????case 'gif': ????????????????imagegif($crop ? $crop : $new, $destination); ????????????????break; ????????} ????????@imagedestroy($image); ????????@imagedestroy($new); ????????@imagedestroy($crop); ????} }PHP最终会返回一个JSON格式的数组,我返回的信息就是图片地址、名称,还有段img的html代码,最后在js那边获取到json数组并处理,至此,操作结束。
文章最开始提到,还有点击选择文件上传和网络图片,因为这2个不属于这次的主题范围内,就不说了。况且这2个功能实现起来都不麻烦。
1 楼 greatghoul 2012-02-02 而已再好点就完美了。