引言

图片存储策略

1. 直接存储图片文件(BLOB类型)

1.1 创建表

CREATE TABLE images (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  image LONGBLOB NOT NULL
);

1.2 插入图片

INSERT INTO images (name, image) VALUES ('example.jpg', LOADFILE('/path/to/example.jpg'));

注意:LOADFILE()函数要求MySQL服务器对指定路径有读取权限,且该路径必须在MySQL服务器的securefilepriv变量指定的目录中。

2. 存储图片路径

2.1 创建表

CREATE TABLE images (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  image_path VARCHAR(255) NOT NULL
);

2.2 插入图片路径

INSERT INTO images (name, image_path) VALUES ('example.jpg', '/path/to/example.jpg');

图片处理技巧

1. 图片缩放

$image = imagecreatefromjpeg('/path/to/example.jpg');
$width = 100;
$height = (int)($height * $width / imagesx($image));
$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));
imagejpeg($image_p, '/path/to/thumbnail.jpg');

2. 图片裁剪

$image = imagecreatefromjpeg('/path/to/example.jpg');
$src_x = 50;
$src_y = 50;
$dst_w = 100;
$dst_h = 100;
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
imagecopyresampled($dst_image, $image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, 200, 200);
imagejpeg($dst_image, '/path/to/cropped.jpg');

3. 图片水印

$image = imagecreatefromjpeg('/path/to/example.jpg');
$text_color = imagecolorallocate($image, 255, 255, 255);
$font_file = 'arial.ttf';
$font_size = 20;
imagettftext($image, $font_size, 0, 10, 30, $text_color, $font_file, 'Watermark');
imagejpeg($image, '/path/to/watermarked.jpg');

总结