WordPress - 업로드 시 이미지 흐림
따라서 업로드 시 WordPress에서 흐릿한 이미지를 만들기 위해 여기에 제시된 예(워터마크 없이 흐릿하게 수정)를 따르고 있습니다.문제는 업로드된 파일의 크기가 설정 크기와 완전히 같거나 작으면 WordPress가 이미지를 생성하지 않기 때문에 흐릿한 파일이 생성되지 않는다는 것입니다.
는 '어느새'를요.isst($meta['sizes']['background-image-blurred']['file'])
copy()
파일은 되지만 WordPress 가 아닌의 경우 WordPress "메타데이터"를 할 때 높이되지 않은 합니다). 따라서 WordPress를 사용하여 표시할 때 높이/너비 정의되지 않은 문제가 발생합니다.wp_get_attachment_image
.
저는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★wp_get_attachment_image
훅은 아마도 잘못된 방법일 것입니다.이미지 업로드 프로세스 초기에 실행해야 할 수 있습니다.
어떻게 하면 이 일을 가장 잘 해낼 수 있을까?
/**
* Several functions relatting to blurring images on uploaded.
* @see https://codeable.io/community/how-to-watermark-wordpress-images-with-imagemagick/
*/
add_image_size( 'background-image-blurred', 1920, 1080, true );
function generate_blurred_image( $meta ) {
$time = substr( $meta['file'], 0, 7); // Extract the date in form "2015/04"
$upload_dir = wp_upload_dir( $time ); // Get the "proper" upload dir
$filename = $meta['sizes']['background-image-blurred']['file'];
$meta['sizes']['background-image-blurred']['file'] = blur_image( $filename, $upload_dir );
return $meta;
}
add_filter( 'wp_generate_attachment_metadata', 'generate_blurred_image' );
function blur_image( $filename, $upload_dir ) {
$original_image_path = trailingslashit( $upload_dir['path'] ) . $filename;
$image_resource = new Imagick( $original_image_path );
$image_resource->gaussianBlurImage( 10, 100 ); // See: http://phpimagick.com/Imagick/gaussianBlurImage
return save_blurred_image( $image_resource, $original_image_path );
}
function save_blurred_image( $image_resource, $original_image_path ) {
$image_data = pathinfo( $original_image_path );
$new_filename = $image_data['filename'] . '-blurred.' . $image_data['extension'];
// Build path to new blurred image
$blurred_image_path = str_replace($image_data['basename'], $new_filename, $original_image_path);
if ( ! $image_resource->writeImage( $blurred_image_path ) ) {
return $image_data['basename'];
}
// Delete the placeholder image WordPress made now that it's been blurred
unlink( $original_image_path );
return $new_filename;
}
유감스럽게도 wp에는 사이즈를 강제하는 필터가 없기 때문에 작성되지 않은 경우 나중에 훅인하여 이미지 크기를 조정하여 메타데이터에 팝업할 수 있습니다.
저는 상상력이 부족하지 않기 때문에 이러한 기능을 직접 사용해 볼 필요가 있습니다.그러나 위의 프로세스는 올바른 것입니다.파일명을 갱신하고 아래 어레이를 입력하기만 하면 됩니다.PS는 필터 내에서 아무것도 출력하지 않습니다!
function custom_img_size(){
add_image_size( 'background-image-blurred', 1920, 1080, true );
}
add_action( 'after_setup_theme', 'custom_img_size' );
add_filter('wp_generate_attachment_metadata', 'force_add_size', 100);
function force_add_size( $metadata ) {
if(!isset($metadata['sizes']['background-image-blurred'])){
//not set so initiate our custom size...
//I dont have imagick installed so just use your functions here to duplicate
//note original file = $filename update the $newfilename below...
//sample resize code ...
$upload_dir = wp_upload_dir();
$filename= $upload_dir['basedir'].'/'.$metadata['file'];
$extension = strtolower(strrchr($metadata['file'], '.'));
$newfilename= str_replace($extension, '-1200x1080', $filename).$extension;
copy($filename, $newfilename );
//end sample resize code.....
$filetype= 'image/jpeg';
$metadata['sizes']['background-image-blurred']= array(
"file"=> $newfilename,
"width"=> 1920,
"height"=> 1080,
"mime-type"=> $filetype
);
}
return $metadata;
}
갱신
이는 기존 필터가 흐릿한 커스텀사이즈를 작성하지 못한 부분만 캡처하도록 설계되어 있습니다.그렇지 않으면 아무것도 실행되지 않습니다.그래도 원래 필터를 포함해야 합니다.원래 코드에 문제가 있을 수 있습니다.필터에서 원본 파일을 삭제 중입니다. 업데이트해야 하는 '_wp_attached_file'이라는 포스트메타 필드가 있기 때문에 문제가 발생합니다.아래에 메모를 첨부했습니다.
필터는 저장하기 전에 메타데이터를 캡처하기 때문에 $metadata를 반환하면 변경사항도 저장됩니다.소스코드(https://core.trac.wordpress.org/browser/tags/3.8.1/src/wp-admin/includes/image.php#L72 를 참조하면, 동작의 구조를 정확하게 확인할 수 있습니다.wp4.3을 사용하는 것도 확인했습니다.
아래에 당신이 필요로 하는 이매직 기능을 삽입해 보았습니다.실제로 어디에도 설치되어 있지 않기 때문에 테스트하지 않았습니다.(실제로는 훌륭한 오픈 소스 프로그램이지만 서버를 많이 사용하는 프로그램입니다).위의 기능 대신 이 기능을 사용해 보십시오.
add_filter('wp_generate_attachment_metadata', 'force_add_size', 100, 2); function force_add_size( $metadata, $id ){ $upload_dir = wp_upload_dir(); $filename= $upload_dir['basedir'].'/'.$metadata['file']; $extension = strtolower(strrchr($metadata['file'], '.')); $newfilename= str_replace($extension, '-blurred', $filename).$extension; $image_resource = new Imagick( $filename); $image_resource->resizeImage(1920,1080,Imagick::FILTER_LANCZOS,.3); $image_resource->writeImage( $newfilename ); //http://www.dylanbeattie.net/magick/filters/result.html unlink( $filename );//delete original image altogether ---> you might want to update the post meta on this '_wp_attached_file' , you can actually get the attachment id from the filter, i have added it above. It would be best to have a actual image url in there! something like $sfile= str_replace($upload_dir['basedir'],'', $newfilename); update_post_meta($id, '_wp_attached_file', $sfile ); switch($extension){ case '.jpg': case '.jpeg': $type = 'image/jpeg'; break; case '.gif': $type = 'image/gif'; break; case '.png': $type = 'image/png'; break; default: $type = 'image/jpeg'; // you might want a conditional to check its actually a image...imagick will do this for you as well....it shouldnt get this far if not a image. break; } $metadata['sizes']['background-image-blurred']= array( "file"=> $newfilename, "width"=> 1920,//your custom image size, has to be this! you could get the global var and check for sizes but its this size in particular we want? "height"=> 1080, "mime-type"=> $type ); return $metadata; }
이미지가 더 작은 크기로 늘어나는 것을 방지하기 위해 업데이트하면 Imagick 코드가 이 코드로 대체됩니다.
$upload_dir = wp_upload_dir();
$filename= $upload_dir['basedir'].'/'.$metadata['file'];
$extension = strtolower(strrchr($metadata['file'], '.'));
$newfilename= str_replace($extension, '-blurred', $filename).$extension;
$image_resource = new Imagick( $filename);
if($image_resource->getImageWidth() <= 1920 || $image_resource->getImageHeight() > <= 1020) {
return $metadata;
}
$image_resource->resizeImage(1920,1080,Imagick::FILTER_LANCZOS,.3);
$image_resource->writeImage( $newfilename );
//http://www.dylanbeattie.net/magick/filters/result.html
처음 질문을 읽었을 때 이미지 설정이나 이미지 생성 또는 둘 다 문제가 있는지 잘 몰랐습니다.했습니다.wp_update_attachment_metadata
후wp_generate_attachment_metadata
대신 새 이미지를 사용하도록 게시합니다.
때, 가 있다는 을 깨달았습니다.add_image_size()
업로드된 이미지보다 크거나 작은 이미지에서 발생하기 때문입니다.새로운 테마의 대체 사이즈 이미지 생성(재)에서도 이 문제가 발생한 적이 있습니다., 둘 중 가 안 .add_image_size()
Wordpress Code Reference에서 이를 확인하고 싶었지만, 아래쪽에 있는 기고자의 코멘트가 게재되어 있지 않지만, 당신이 직면하고 있는 문제와 정확히 일치하고 있는 것을 발견했습니다.
크롭이 true로 설정되어 있을 때 치수가 add_image_size()와 일치하는 이미지를 업로드하면 wp_generate_attachment_metadata 필터에 의해 액세스되는 $meta 오브젝트에 일치하는 이미지 크기를 사용할 수 없습니다.또, 업로드 한 사진보다 큰 사이즈의 화상도 사용할 수 없게 됩니다.
(따라서 흑백의 파생 화상등의 작성 방법을 사용하고 있는 경우는, 업 로드한 화상의 사이즈가 흑백의 화상의 사이즈와 같으면 동작시킬 수 없습니다.
당신의 경우 Imagick을 사용하고 있기 때문에 이미지 계산을 할 수 있는 회피책이 있다고 생각합니다.「 」의 borderImage
기능은 업로드한 이미지보다 최대 1픽셀 큰 각 이미지에 테두리를 추가하는 것만으로 끝납니다. ★★★★★★★★★★★★★★★★★.add_image_size()
크기를 필요한 크기로 조정하여 문제를 해결할 수 있도록 기본적으로 가운데에서 잘라냅니다.
1920 x 1080으로 하다 Imagick 사용 ★★getSize
이치노예를 들어 1920 x 1080 이지만, 이것이 흐릿함을 유발하지는 않습니다. 이렇게 쓰면서borderImage
이미지에 1픽셀의 흰색 테두리를 추가합니다.잘라내기가 참으로 설정되어 있는 한 워드 프레스를 트리거하여 이미지의 크기를 1920 x 1080으로 조정합니다.
이미지가 더 작지만 필요한 크기에 비교적 가까운 경우 테두리를 10픽셀 정도로 만들고 크기를 채우고 워드프레스를 중앙에서 잘라냅니다.이것은 비례 이미지에서만 작동합니다.
이미지가 조금 작은 경우(예를 들어 200 x 800), 다른 이미지를 추가하는 것을 검토해야 합니다.add_image_size()
옵션에서 작은 이미지를 처리합니다.앞으로 나아가야 할 경우 Imagick을 사용하여 이미지를 필요한 비율로 "확장"하거나 필요한 크기의 새로운 흰색 Imagick 캔버스를 생성하여 이미지를 왼쪽 상단으로 오버레이하여 새로운 이미지의 오른쪽 아래에 공백을 둘 수 있습니다.그런 다음 add_image_size crop 파라미터를 사용하여 여분의 흰색을 잘라냅니다.예를들면,add_image_size('background-image-blurred', 1920, 1080, array('left','top'))
이미지 왼쪽 위에서부터 자르기 설정을 합니다.
왜 1×1 또는 5×5 사이즈의 이미지를 가지고 있지 않은지 조금 속여야 합니다.그래서 이미지가 어떤 것이든 그 이미지의 섬네일이 생성됩니다.
또한 'wp_generate_attachment_metadata'에서 Stuff를 해킹하여 원본 이미지에서 이미지를 생성하고 1 x 1 이미지를 원하는 Blured 이미지로 바꿉니다.표시 또는 기타 계산 목적으로 "background-image-blurred"를 사용하는 경우 필터를 통해 트릭해야 합니다.
내 생각에 조금 엉터리지만 제대로 작동해야 할 것 같아.
wp_handle_upload() 함수에 초점을 맞추는 것은 어떨까요?
즉, 이미지만 흐리게 하고 이미지에 다른 변경은 하지 않기 때문에 서버상에 다른 이미지를 작성하는 대신 CSS가 다리 작업을 하도록 하는 것은 어떨까요?
.heroBackgroundImage {
background: url('uploadedimage.jpg');
-webkit-filter: blur(8px);
-moz-filter: blur(8px);
-o-filter: blur(8px);
-ms-filter: blur(8px);
filter: blur(8px);
-webkit-transform: translate3d(0,0,0);
}
서버 작업을 줄이고 클라이언트 측에서 처리하도록 합니다.
편집: 방금 당신의 코멘트가 CSS일 리가 없습니다.효과를 GPU로 이동시키기 위해 webkit-transform이 추가되어 렌더링 효율이 향상되었습니다.그렇지 않으면, 여전히 후세를 위해 저축하고 있다.
참조하는 예에서는 워드프레스 필터를 사용합니다.
문제는 워드프레스 필터는 항상 특정 이미지 해상도에 바인딩되기 때문에 해상도에 관계없이 이미지를 처리할 수 없다는 것입니다.
필터는 피하는 것이 좋습니다.대신 이미지를 이전 시점으로 사전 처리합니다.워드프레스로 제어권을 넘기기 전에 먼저 이미지를 흐리게 하는 샘플 코드를 아래에서 찾으십시오.
// perform new upload
include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true);
$filename = $uniq_name.'.'.$imagetype;
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);
// apply blur
$image_resource = new Imagick( $uploadfile );
$image_resource->resizeImage(500, 500, null, 1);
$image_resource->blurImage( 40, 20 );
$image_data = pathinfo( $uploadfile );
$new_filename = $image_data['filename'] . '-blur.' . $image_data['extension'];
$blur_image_path = str_replace($image_data['basename'], $new_filename, $uploadfile);
if ( ! $image_resource->writeImage( $blur_image_path ) ) {
unlink( $uploadfile );
return ""; // fixme
}
unlink( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $imageurlHash,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $blur_image_path );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
언급URL : https://stackoverflow.com/questions/34377231/wordpress-blur-image-on-upload
'source' 카테고리의 다른 글
오류: PostCSS 플러그인 자동 리픽서에는 PostCSS 8이 필요합니다. PostCSS를 업데이트하거나 이 플러그인을 다운그레이드하십시오. (0) | 2023.02.14 |
---|---|
Woocommerce가 카트 후크에 추가되었습니다(제품이 카트에 정상적으로 추가된 후). (0) | 2023.02.14 |
워드프레스 필터 문서?add_filter()를 이해하려고 합니다. (0) | 2023.02.14 |
Angular에서 객체를 푸시하는 방법ngRepeat 어레이 간의 JS (0) | 2023.02.14 |
AngularJS: 부모 스코프가 (격리된 스코프를 사용하여) 양방향 바인딩으로 업데이트되지 않음 (0) | 2023.02.14 |