focal_point.smartcrop.inc in Focal Point 7
File
focal_point.smartcrop.inc
View source
<?php
include_once drupal_get_path('module', 'smartcrop') . '/image.gd.inc';
function focal_point_smartcrop_estimation(stdClass $image_data) {
static $px_needed = 500;
$image_data = clone $image_data;
if (image_get_toolkit() != 'gd') {
image_gd_load($image_data);
}
$image_width = $image_data->info['width'];
$image_height = $image_data->info['height'];
$ratio = max($px_needed / $image_width, $px_needed / $image_height);
$resized = FALSE;
if ($ratio <= 1) {
$resized = image_gd_resize($image_data, round($ratio * $image_width), round($ratio * $image_height));
}
$full_width = imagesx($image_data->resource);
$full_height = imagesy($image_data->resource);
static $highest_ratio = 4;
static $largest_ratio = 4;
$target_width = round($full_height / $highest_ratio);
$target_height = round($full_width / $largest_ratio);
static $slices_count = 25;
$area_width = $full_width / $slices_count;
$area_height = $full_height / $slices_count;
$area_entropies = array();
for ($i = 0; $i < $slices_count; $i++) {
$area_entropies[$i] = array();
for ($j = 0; $j < $slices_count; $j++) {
$area_entropies[$i][$j] = _smartcrop_gd_entropy_slice($image_data, round($i * $area_width), round($j * $area_height), $area_width, $area_height);
}
}
$target_areas_counts = array(
ceil(min($target_width / $area_width, $slices_count)),
ceil(min($target_height / $area_height, $slices_count)),
);
$best_first_area = _focal_point_smartcrop_get_best_first_area($area_entropies, $target_areas_counts);
$x = $area_width * ($best_first_area[0] + $target_areas_counts[0] / 2);
$y = $area_height * ($best_first_area[1] + $target_areas_counts[1] / 2);
if ($resized) {
$x = $x / $ratio;
$y = $y / $ratio;
}
return array(
round($x),
round($y),
);
}
function _focal_point_smartcrop_get_best_first_area($area_entropies, $target_areas_counts) {
$slices_count = count($area_entropies);
$best_entropy = -1;
for ($i = 0; $i <= $slices_count - $target_areas_counts[0]; $i++) {
for ($j = 0; $j <= $slices_count - $target_areas_counts[1]; $j++) {
$first_area = array(
$i,
$j,
);
$entropy = _focal_point_smartcrop_sum_entropies($area_entropies, $first_area, $target_areas_counts);
if ($entropy > $best_entropy) {
$best_entropy = $entropy;
$best_first_area = $first_area;
}
}
}
return $best_first_area;
}
function _focal_point_smartcrop_sum_entropies($area_entropies, $first_area, $target_areas_counts) {
$entropy = 0;
for ($i = 0; $i < $target_areas_counts[0]; $i++) {
for ($j = 0; $j < $target_areas_counts[1]; $j++) {
$entropy += $area_entropies[$first_area[0] + $i][$first_area[1] + $j];
}
}
return $entropy;
}