/** * Upload image and auto create thumbnail. * * @param $field * @param $path * @param null $width * @param null $height * @return string * * @require "intervention/images:~2" */ function upload_image($field, $path, $width = null, $height = null) { $file = input()->file($field); $filename = get_random_filename($file); if (!is_null($width) && !is_null($height)) { $thumbnailPath = $path . '/thumbnail/'; if (!files()->isDirectory($thumbnailPath)) { files()->makeDirectory($thumbnailPath); } $filenPath = public_path($thumbnailPath . $filename); Image::make($file->getRealPath())->resize($width, $height)->save($filenPath); } $file->move($path, $filename); return $filename; }
function get_random_filename($dir, $file_ext) { if (!$dir or !file_exists($dir)) { return false; } $dir = rtrim($dir, '/') . '/'; $filename = md5(mt_rand(1, 99999999) . microtime()); if (file_exists($dir . $filename . '.' . $file_ext)) { return get_random_filename($dir, $file_ext); } return $filename . '.' . $file_ext; }
public function copy_attach($old_type, $new_type, $id, $uid) { $attachs = $this->model('publish')->get_attach($old_type, $id, null); if (!$attachs) { return false; } if ($now) { $now += 1; } else { static $now; $now = time(); } $attach_access_key = md5($uid . $now); foreach ($attachs as $attach) { $new_dir = get_setting('upload_dir') . '/' . $new_type . ($new_type == 'question' ? 's' : '') . '/' . gmdate('Ymd', $now) . '/'; $file_ext = end(explode('.', $attach['file_location'])); $new_filename = get_random_filename($new_dir, $file_ext); if (@make_dir($new_dir) and @copy($attach['path'], $new_dir . $new_filename)) { if ($attach['is_image']) { $old_dir = dirname($attach['path']) . '/'; foreach (AWS_APP::config()->get('image')->attachment_thumbnail as $key => $val) { $thumb_pre = $val['w'] . 'x' . $val['h'] . '_'; @copy($old_dir . $thumb_pre . $attach['file_location'], $new_dir . $thumb_pre . $new_filename); } } $this->model('publish')->add_attach($new_type, $attach['file_name'], $attach_access_key, $now, $new_filename, $attach['is_image']); } } return $attach_access_key; }