Skip to content

Commit

Permalink
version 0.1.2
Browse files Browse the repository at this point in the history
  • Loading branch information
engram-design committed Feb 24, 2016
1 parent 60b0f20 commit 58e14dd
Show file tree
Hide file tree
Showing 10 changed files with 207 additions and 199 deletions.
11 changes: 11 additions & 0 deletions changelog.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
[
{
"version": "0.1.2",
"downloadUrl": "https://github.com/engram-design/ImageResizer/archive/0.1.2.zip",
"date": "2016-02-24 23:15:00",
"notes": [
"[Added] Added support for Amazon S3, Rackspace Cloud Files, and Google Cloud Storage asset sources.",
"[Improved] Using `assets.onBeforeUploadAsset` instead of `assets.onSaveAsset`.",
"[Improved] Elements now auto-refresh after crop or resize.",
"[Improved] Refactoring for better performance."
]
},
{
"version": "0.1.1",
"downloadUrl": "https://github.com/engram-design/ImageResizer/archive/0.1.1.zip",
Expand Down
38 changes: 29 additions & 9 deletions imageresizer/ImageResizerPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public function getName()

public function getVersion()
{
return '0.1.1';
return '0.1.2';
}

public function getSchemaVersion()
Expand Down Expand Up @@ -87,19 +87,39 @@ public function onBeforeInstall()

public function init()
{
craft()->on('assets.onSaveAsset', function(Event $event) {
$asset = $event->params['asset'];
craft()->on('assets.onBeforeUploadAsset', function(Event $event) {
$path = $event->params['path'];
$folder = $event->params['folder'];
$filename = $event->params['filename'];

// If we've triggered this from our cropping action, don't resize too
if (craft()->httpSession->get('ImageResizer_CropElementAction')) {
craft()->httpSession->remove('ImageResizer_CropElementAction');
return true;
}

if (craft()->imageResizer->getSettings()->enabled) {
// If this has been trigged from the element actions, bypass everything below
if (!craft()->httpSession->get('ImageResizer_ResizeElementAction')) {
// Make sure we check out config setting
if (craft()->imageResizer->getSettings()->enabled) {

// Only process if it's a new asset being saved.
if ($event->params['isNewAsset']) {
// Should we be modifying images in this source?
$assetSources = craft()->imageResizer->getSettings()->assetSources;

// Is this a manipulatable image?
if (ImageHelper::isImageManipulatable(IOHelper::getExtension($asset->filename))) {
craft()->imageResizer->resize($asset);
if ($assetSources != '*') {
if (!in_array($folder->source->id, $assetSources)) {
return true;
}
}
}
} else {
// If we are from a element action - delete this so it doesn't persist
craft()->httpSession->remove('ImageResizer_ResizeElementAction');
}

// Is this a manipulatable image?
if (ImageHelper::isImageManipulatable(IOHelper::getExtension($filename))) {
craft()->imageResizer_resize->resize($path);
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion imageresizer/controllers/ImageResizerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function actionCropSaveAction()
if ($assetId) {
$asset = craft()->assets->getFileById($assetId);

$result = craft()->imageResizer->crop($asset, $x1, $x2, $y1, $y2);
$result = craft()->imageResizer_crop->crop($asset, $x1, $x2, $y1, $y2);

if ($result) {
$this->returnJson(array('success' => true));
Expand Down
1 change: 1 addition & 0 deletions imageresizer/resources/css/CropElementAction.css
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
position: absolute;
top: 50%;
margin: -24px;
z-index: 1000;
}

.image-resizer-crop-modal .footer {
Expand Down
4 changes: 4 additions & 0 deletions imageresizer/resources/js/CropElementAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,12 +170,16 @@ Craft.CropImageModal = Garnish.Modal.extend(
params['assetId'] = $(this.$selectedItems).data('id');
}

this.$body.find('.spinner').removeClass('hidden');

Craft.postActionRequest('imageResizer/cropSaveAction', params, $.proxy(function(response, textStatus) {
if (textStatus == 'success') {
if (response.error) {
Craft.cp.displayError(response.error);
} else {
Craft.cp.displayNotice(Craft.t('Image cropped successfully.'));

Craft.elementIndex.updateElements();
}
}

Expand Down
77 changes: 34 additions & 43 deletions imageresizer/resources/js/ResizeElementAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,25 +85,25 @@ Craft.ResizeModal = Garnish.Modal.extend({

this.$footerSpinner.removeClass('hidden');

Craft.postActionRequest('imageResizer/resizeElementAction', { assetIds: dataIds }, $.proxy(function(response, textStatus) {
Craft.postActionRequest('imageResizer/resizeElementAction', { assetIds: dataIds }, $.proxy(function(response, textStatus) {}, this));

new Craft.ResizeTaskProgress(this, function() {
modal.$footerSpinner.addClass('hidden');

// In this case, no images were resized at all!
if (modal.$body.find('.task').length == 0) {
var $container = $('<div class="task"/>').appendTo(modal.$body.find('.main'));
var $statusContainer = $('<div class="task-status"/>').appendTo($container);
$('<div><div data-icon="check"> ' + Craft.t('No images to resize!') + '</div>').appendTo($statusContainer);
}
new Craft.ResizeTaskProgress(this, function() {
modal.$footerSpinner.addClass('hidden');

// In this case, no images were resized at all!
if (modal.$body.find('.task').length == 0) {
var $container = $('<div class="task"/>').appendTo(modal.$body.find('.main'));
var $statusContainer = $('<div class="task-status"/>').appendTo($container);
$('<div><div data-icon="check"> ' + Craft.t('No images to resize!') + '</div>').appendTo($statusContainer);
}

setTimeout($.proxy(function() {
modal.onFadeOut();
}), 1000);

});
setTimeout($.proxy(function() {
modal.onFadeOut();

}, this));
Craft.elementIndex.updateElements();
}), 1000);

});
}
});

Expand All @@ -124,15 +124,20 @@ Craft.ResizeTaskProgress = Garnish.Base.extend({
this.tasksById = {};
this.completedTasks = [];

this.updateTasks();
// Force the tasks icon to run
setTimeout($.proxy(function() {
this.updateTasks();
}, this), 1000);

Craft.cp.stopTrackingTaskProgress();
},

updateTasks: function() {
this.completed = false;

Craft.postActionRequest('tasks/getTaskInfo', $.proxy(function(taskInfo, textStatus) {
if (textStatus == 'success') {
this.showTaskInfo(taskInfo);
this.showTaskInfo(taskInfo[0]);
}
}, this))
},
Expand All @@ -142,9 +147,7 @@ Craft.ResizeTaskProgress = Garnish.Base.extend({
var newTaskIds = [];

if (taskInfo) {
for (var i = 0; i < taskInfo.length; i++) {
newTaskIds.push(taskInfo[i].id);
}
newTaskIds.push(taskInfo.id);
}

for (var id in this.tasksById) {
Expand All @@ -156,32 +159,20 @@ Craft.ResizeTaskProgress = Garnish.Base.extend({
}

// Now display the tasks that are still around
if (taskInfo && taskInfo.length) {
if (taskInfo) {
var anyTasksRunning = false,
anyTasksFailed = false;

for (var i = 0; i < taskInfo.length; i++) {
var info = taskInfo[i];

if (!anyTasksRunning && info.status == 'running') {
anyTasksRunning = true;
} else if (!anyTasksFailed && info.status == 'error') {
anyTasksFailed = true;
}
if (!anyTasksRunning && taskInfo.status == 'running') {
anyTasksRunning = true;
} else if (!anyTasksFailed && taskInfo.status == 'error') {
anyTasksFailed = true;
}

if (this.tasksById[info.id]) {
this.tasksById[info.id].updateStatus(info);
} else {
this.tasksById[info.id] = new Craft.ResizeTaskProgress.Task(this.modal, info);

// Place it before the next already known task
for (var j = i + 1; j < taskInfo.length; j++) {
if (this.tasksById[taskInfo[j].id]) {
this.tasksById[info.id].$container.insertBefore(this.tasksById[taskInfo[j].id].$container);
break;
}
}
}
if (this.tasksById[taskInfo.id]) {
this.tasksById[taskInfo.id].updateStatus(taskInfo);
} else {
this.tasksById[taskInfo.id] = new Craft.ResizeTaskProgress.Task(this.modal, taskInfo);
}

if (anyTasksRunning) {
Expand Down
147 changes: 3 additions & 144 deletions imageresizer/services/ImageResizerService.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,144 +16,11 @@ public function getSettings()
return $this->getPlugin()->getSettings();
}

public function resize($asset)
public function getImageQuality($filename, $quality = null)
{
try {
// Get the full path of the asset we want to resize
$path = $this->_getImagePath($asset);
$desiredQuality = (!$quality) ? craft()->imageResizer->getSettings()->imageQuality : $quality;

// If the path is false, we're not allowed to modify images in the source - kill it!
if (!$path) {
return true;
}

$image = craft()->images->loadImage($path);

// Our maximum width/height for assets from plugin settings
$imageWidth = $this->getSettings()->imageWidth;
$imageHeight = $this->getSettings()->imageHeight;

// Lets check to see if this image needs resizing. Split into two steps to ensure
// proper aspect ratio is preserved and no upscaling occurs.
$hasResized = false;

if ($image->getWidth() > $imageWidth) {
$hasResized = true;
$this->_resizeImage($image, $imageWidth, null);
}

if ($image->getHeight() > $imageHeight) {
$hasResized = true;
$this->_resizeImage($image, null, $imageHeight);
}

if ($hasResized) {
// Set image quality - but normalise (for PNG)!
$quality = $this->_getImageQuality($asset);
$image->setQuality($quality);

$image->saveAs($path);

// Update the asset record to reflect changes
$this->_updateAsset($asset, $image, $path);
}

return $asset;
} catch (\Exception $e) {
ImageResizerPlugin::log($e->getMessage(), LogLevel::Error, true);

return false;
}
}

public function crop($asset, $x1, $x2, $y1, $y2)
{
// Get the full path for the asset being uploaded
$source = $asset->getSource();

// Can only deal with local assets for now
if ($source->type != 'Local') {
return false;
}

$sourcePath = craft()->config->parseEnvironmentString($source->settings['path']);
$folderPath = $asset->getFolder()->path;

$path = $sourcePath . $folderPath . $asset->filename;

// Memory checking
if (craft()->images->checkMemoryForImage($path)) {

$image = craft()->images->loadImage($path);

// Make sure that image quality isn't messed with for cropping
$quality = $this->_getImageQuality($asset, 100);
$image->setQuality($quality);

// Do the cropping
$image->crop($x1, $x2, $y1, $y2);
$image->saveAs($path);

// Update the asset record to reflect changes
$this->_updateAsset($asset, $image, $path);

return true;
} else {
return false;
}
}


// Private Methods
// =========================================================================

private function _updateAsset($asset, $image, $path)
{
// Update our model
$asset->size = IOHelper::getFileSize($path);
$asset->width = $image->getWidth();
$asset->height = $image->getHeight();

// Then, make sure we update the asset info as stored in the database
$fileRecord = AssetFileRecord::model()->findById($asset->id);
$fileRecord->size = $asset->size;
$fileRecord->width = $asset->width;
$fileRecord->height = $asset->height;
$fileRecord->dateModified = IOHelper::getLastTimeModified($path);

$fileRecord->save(false);
}

private function _getImagePath($asset)
{
// Get the full path for the asset being uploaded
$source = $asset->getSource();

// Can only deal with local assets for now
if ($source->type != 'Local') {
return false;
}

// Should we be modifying images in this source?
$assetSources = $this->getSettings()->assetSources;

if ($assetSources != '*') {
if (!in_array($source->id, $assetSources)) {
return false;
}
}

$sourcePath = craft()->config->parseEnvironmentString($source->settings['path']);
$folderPath = $asset->getFolder()->path;

return $sourcePath . $folderPath . $asset->filename;
}

private function _getImageQuality($asset, $quality = null)
{
$desiredQuality = (!$quality) ? $this->getSettings()->imageQuality : $quality;

if ($asset->getExtension() == 'png') {
if (IOHelper::getExtension($filename) == 'png') {
// Valid PNG quality settings are 0-9, so normalize and flip, because we're talking about compression
// levels, not quality, like jpg and gif.
$quality = round(($desiredQuality * 9) / 100);
Expand All @@ -172,12 +39,4 @@ private function _getImageQuality($asset, $quality = null)

return $quality;
}

private function _resizeImage(&$image, $width, $height)
{
// Calculate the missing width/height for the asset - ensure aspect ratio is maintained
$dimensions = ImageHelper::calculateMissingDimension($width, $height, $image->getWidth(), $image->getHeight());

$image->resize($dimensions[0], $dimensions[1]);
}
}
Loading

0 comments on commit 58e14dd

Please sign in to comment.