为 WordPress 主题集成图片压缩功能

WordPress4515阅读模式

文章配图是个让人烦心的事,不仅占用空间,再则找个与内容贴切的图片,真不是个容易的事,一般我都是先把文章发表,有时间再弄图。

说正题,WordPress 默认上传图片时,有一定压缩效果,但并不理想,如果懒得在本地用软件压缩图片,WordPress有众多的图片压缩插件可供选择,比如reSmush、EWWW Image Optimizer、Compress JPEG & PNG等,不过插件体积较大,只想压缩一下图片,结果复杂的设置,多余的功能,让人眼花缭乱,有些还要调用外部API压缩算法,影响速度。

本文分享一段代码用于后台本地上传图片时,调整压缩图片尺寸大小。

为 WordPress 主题集成图片压缩功能-图片1

集成图片压缩功能

将代码添加到当前主题函数模板 functions.php 即可。

之后进入WP后台 → 设置 → 图片压缩,进入图片压缩设置页面,适当调整一下最大图片尺寸和压缩级别。

压缩就会造成画质下降,所谓无损压缩就是个噱头而已。

 

为 WordPress 主题集成图片压缩功能-图片2

// 图片压缩 zmingcx.com
add_option( 'zm_resizeupload_width', 				'1200', '', 'yes' );
add_option( 'zm_resizeupload_height',				'1200', '', 'yes' );
add_option( 'zm_resizeupload_quality',				'90', '', 'yes' );
add_option( 'zm_resizeupload_resize_yesno', 		'yes', '','yes' );
add_option( 'zm_resizeupload_recompress_yesno', 	'yes', '','yes' );

add_action( 'admin_menu', 'zm_uploadresize_options_page' );

// 挂钩到上传
add_action( 'wp_handle_upload', 'zm_uploadresize_resize' );

function zm_uploadresize_options_page() {
	global $zm_settings_page;
	if( function_exists( 'add_options_page' ) ) {
		$zm_settings_page = add_options_page(
			'图片压缩',
			'<span class="bem"></span>图片压缩',
			'manage_options',
			'resize-after-upload',
			'zm_uploadresize_options'
		);
	}
}

// 定义选项页面
function zm_uploadresize_options() {
	if( isset( $_POST['zm_options_update'] ) ) {
		if ( ! ( current_user_can( 'manage_options' ) && wp_verify_nonce( $_POST['_wpnonce'], 'zm-options-update' ) ) ) {
			wp_die( "无权限" );
		}

		$resizing_enabled = ( $_POST['yesno'] == 'yes' ? 'yes' : 'no' );
		$force_jpeg_recompression   = ( $_POST['recompress_yesno'] == 'yes' ? 'yes' : 'no' );

		$max_width   = intval( $_POST['maxwidth'] );
		$max_height  = intval( $_POST['maxheight'] );
		$compression_level    = intval( $_POST['quality'] );

		// 如果输入不是整数,使用默认设置
		$max_width = ( $max_width == '' ) ? 0 : $max_width;
		$max_width = ( ctype_digit( strval( $max_width ) ) == false) ? get_option( 'zm_resizeupload_width' ) : $max_width;
		update_option( 'zm_resizeupload_width', $max_width );

		$max_height = ( $max_height == '' ) ? 0 : $max_height;
		$max_height = (ctype_digit(strval($max_height)) == false) ? get_option('zm_resizeupload_height') : $max_height;
		update_option( 'zm_resizeupload_height',$max_height );

		$compression_level = ( $compression_level == '' ) ? 1 : $compression_level;
		$compression_level = ( ctype_digit( strval( $compression_level ) ) == false ) ? get_option( 'zm_resizeupload_quality' ) : $compression_level;

		if( $compression_level < 1 ) {
			$compression_level = 1;
		} else if( $compression_level > 100 ) {
			$compression_level = 100;
		}

		update_option( 'zm_resizeupload_quality', $compression_level );

		if ( $resizing_enabled == 'yes' ) {
			update_option( 'zm_resizeupload_resize_yesno','yes' );
		} else {
			update_option( 'zm_resizeupload_resize_yesno','no' );
		}

		if ( $force_jpeg_recompression == 'yes' ) {
			update_option( 'zm_resizeupload_recompress_yesno','yes' );
		} else {
			update_option( 'zm_resizeupload_recompress_yesno','no' );
		}
	    echo('<div id="message" class="updated fade"><p><strong>设置已保存。</strong></p></div>');
	}

	// 设置表单
	$resizing_enabled = get_option( 'zm_resizeupload_resize_yesno' );
	$force_jpeg_recompression = get_option( 'zm_resizeupload_recompress_yesno' );
	$compression_level  = intval( get_option('zm_resizeupload_quality' ) );

	$max_width = get_option( 'zm_resizeupload_width' );
	$max_height = get_option( 'zm_resizeupload_height' );
	?>

	<div class="wrap">
		<form method="post" accept-charset="utf-8">
			<h1>图片压缩设置</h1>
			<h3>大小设置</h3>
			<table class="form-table">
				<tr>
					<th scope="row">调整大小</th>
					<td valign="top">
						<select name="yesno" id="yesno">
							<option value="no" label="否" <?php echo ( $resizing_enabled == 'no' ) ? 'selected="selected"' : ''; ?>></option>
							<option value="yes" label="是" <?php echo ( $resizing_enabled == 'yes' ) ? 'selected="selected"' : ''; ?>></option>
						</select>
					</td>
				</tr>

				<tr>
					<th scope="row">最大图片尺寸</th>
					<td>
						<label for="maxwidth">最大宽度</label>
						<input name="maxwidth" step="1" min="0" id="maxwidth" class="small-text" type="number" value="<?php echo $max_width; ?>">
						&nbsp;&nbsp;&nbsp;<label for="maxheight">最大高度</label>
						<input name="maxheight" step="1" min="0" id="maxheight" class="small-text" type="number" value="<?php echo $max_height; ?>">
						<p class="description">设置为零即不调整大小,</p>
					</td>
				</tr>
			</table>

			<h3>JPEG 压缩设置</h3>
			<table class="form-table">
				<tr>
					<th scope="row">压缩级别</th>
					<td valign="top">
						<select id="quality" name="quality">
						<?php for( $i=1; $i<=100; $i++ ) : ?>
							<option value="<?php echo $i; ?>" <?php if( $compression_level == $i ) : ?>selected<?php endif; ?>><?php echo $i; ?></option>
						<?php endfor; ?>
						</select>
					</td>
				</tr>

				<tr>
					<th scope="row">重新压缩</th>
					<td>
						<select name="recompress_yesno" id="yesno">
							<option value="no" label="否" <?php echo ($force_jpeg_recompression == 'no') ? 'selected="selected"' : ''; ?>></option>
							<option value="yes" label="是" <?php echo ($force_jpeg_recompression == 'yes') ? 'selected="selected"' : ''; ?>></option>
						</select>
					</td>
				</tr>
			</table>

			<p class="submit">
				<input type="hidden" id="convert-bmp" name="convertbmp" value="no" />
				<input type="hidden" name="action" value="update" />
				<?php wp_nonce_field('zm-options-update'); ?>
				<input id="submit" name="zm_options_update" class="button button-primary" type="submit" value="保存更改">
			</p>
		</form>
	</div>
	<?php
}

// 处理图片函数
function zm_uploadresize_resize( $image_data ) {
	$resizing_enabled = get_option( 'zm_resizeupload_resize_yesno' );
	$resizing_enabled = ( $resizing_enabled =='yes' ) ? true : false;

	$force_jpeg_recompression = get_option( 'zm_resizeupload_recompress_yesno' );
	$force_jpeg_recompression = ( $force_jpeg_recompression=='yes' ) ? true : false;

	$compression_level = get_option( 'zm_resizeupload_quality' );

	$max_width  = get_option( 'zm_resizeupload_width' )==0 ? false : get_option( 'zm_resizeupload_width' );
	$max_height = get_option( 'zm_resizeupload_height' )==0 ? false : get_option( 'zm_resizeupload_height' );

	if ( $resizing_enabled || $force_jpeg_recompression ) {
		$fatal_error_reported = false;
		$valid_types = array( 'image/gif','image/png','image/jpeg','image/jpg' );

		if ( empty( $image_data['file'] ) || empty( $image_data['type'] ) ) {
			$fatal_error_reported = true;
		} else if( !in_array( $image_data['type'], $valid_types ) ) {
			$fatal_error_reported = true;
		}

		$image_editor = wp_get_image_editor( $image_data['file'] );
		$image_type = $image_data['type'];

		if ( $fatal_error_reported || is_wp_error( $image_editor ) ) {
		} else {
			$to_save = false;
			$resized = false;


			// 如果需要,执行调整大小
			if ( $resizing_enabled ) {
				$sizes = $image_editor->get_size();

				if ( ( isset( $sizes['width'] ) && $sizes['width'] > $max_width ) || ( isset( $sizes['height']) && $sizes['height'] > $max_height ) ) {
					$image_editor->resize($max_width, $max_height, false);
					$resized = true;
					$to_save = true;
					$sizes = $image_editor->get_size();
				}
			}

			// 无论调整大小,重新压缩时都必须保存图像
			if ( $force_jpeg_recompression && ( $image_type=='image/jpg' || $image_type=='image/jpeg' ) ) {
				$to_save = true;
			}

			// 仅在调整大小或需要重新压缩时才保存图像
			if ( $to_save ) {
				$image_editor->set_quality( $compression_level );
				$saved_image = $image_editor->save( $image_data['file'] );
			}
		}
	}
	return $image_data;
}

function zm_uploadresize_convert_image( $params, $compression_level ) {
	$transparent = 0;
	$image = $params['file'];

	$contents = file_get_contents( $image );
	if ( ord ( file_get_contents( $image, false, null, 25, 1 ) ) & 4 ) $transparent = 1;
	if ( stripos( $contents, 'PLTE' ) !== false && stripos( $contents, 'tRNS' ) !== false ) $transparent = 1;

	$transparent_pixel = $img = $bg = false;
	if ( $transparent ) {
		$img = imagecreatefrompng( $params['file'] );
		$w = imagesx( $img ); // Get the width of the image
		$h = imagesy( $img ); // Get the height of the image
	    //run through pixels until transparent pixel is found:
		for( $i = 0; $i<$w; $i++ ) {
			for( $j = 0; $j < $h; $j++ ) {
				$rgba = imagecolorat( $img, $i, $j );
				if( ( $rgba & 0x7F000000) >> 24 ) {
					$transparent_pixel = true;
					break;
				}
			}
		}
	}

	if ( !$transparent || !$transparent_pixel ) {
		if (!$img) $img = imagecreatefrompng( $params['file'] );
		$bg = imagecreatetruecolor(imagesx( $img ), imagesy( $img ) );
		imagefill( $bg, 0, 0, imagecolorallocate( $bg, 255, 255, 255 ) );
		imagealphablending( $bg, 1 );
		imagecopy( $bg, $img, 0, 0, 0, 0, imagesx( $img ), imagesy( $img ) );
		$newPath = preg_replace("/\.png$/", ".jpg", $params['file'] );
		$newUrl = preg_replace( "/\.png$/", ".jpg", $params['url'] );
		for($i = 1; file_exists( $newPath ); $i++) {
			$newPath = preg_replace( "/\.png$/", "-".$i.".jpg", $params['file'] );
		}
		if ( imagejpeg( $bg, $newPath, $compression_level ) ){
			unlink( $params['file'] );
			$params['file'] = $newPath;
			$params['url'] = $newUrl;
			$params['type'] = 'image/jpeg';
		}
	}
	return $params;
}

代码取自Resize Image After Upload插件

开启压缩功能后,上传图片比正常要稍慢一些,因为在处理压缩图片,不过效果还是很明显,在保留原尺寸的情况下,较大的图片至少也会压缩60%,压缩功能仅限JPEG格式。

想压缩优化之前上传的图片,上述代码无法实现,可以安装相关插件进行批量压缩,比如:Imsanity

为 WordPress 主题集成图片压缩功能-图片3
在上传图片时,使用 Imsanity 可以自动调整图像大小,并可以批量压缩调整现有图片大小尺寸,释放磁盘空间,插件使用 Wo...
454

或者

WordPress 图片优化和压缩插件:Smush
主要功能是可以在线批量压缩图片,并可以在WP后台选择一个附件目录对其中的图片进行压缩。 下面是官网说明: 优化图像,打开延迟...
7363

 

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  4  访客  3  作者  1
    • 轨魅网
      轨魅网 2

      一直坚持用我的右手压缩。 :grin:

      • maqingxi
        maqingxi 5

        网页展示,图片的尺寸其实不用太大。

      匿名

      发表评论

      匿名网友
      :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

      拖动滑块以完成验证