Gallery Manager extension

I have changed galleryManager.js in this way:


        if (window.FormData !== undefined) { // if XHR2 available

            var uploadFileName = $('.afile', $gallery).attr('name');


            function multiUpload(files) {

                if (files.length == 0) return;

                $progressOverlay.show();

                $uploadProgress.css('width', '5%');

                var filesCount = files.length;

                var uploadedCount = 0;

                var ids = [];

                for (var i = 0; i < filesCount; i++) {

                	

                	// Checking all the possible window objects needed for file api

                	if (window.File && window.FileReader && window.FileList && window.Blob) {

                		

                		var file = files[i];

                		var reader = new FileReader();

                	    reader.onloadend = function() {

                	 

                	    var tempImg = new Image();

                	    tempImg.src = reader.result;

                	    tempImg.onload = function() {

                	 

                	        var MAX_WIDTH = 400;

                	        var MAX_HEIGHT = 300;

                	        var tempW = tempImg.width;

                	        var tempH = tempImg.height;

                	        if (tempW > tempH) {

                	            if (tempW > MAX_WIDTH) {

                	               tempH *= MAX_WIDTH / tempW;

                	               tempW = MAX_WIDTH;

                	            }

                	        } else {

                	            if (tempH > MAX_HEIGHT) {

                	               tempW *= MAX_HEIGHT / tempH;

                	               tempH = MAX_HEIGHT;

                	            }

                	        }

                	 

                	        var canvas = document.createElement('canvas');

                	        canvas.width = tempW;

                	        canvas.height = tempH;

                	        var ctx = canvas.getContext("2d");

                	        ctx.drawImage(this, 0, 0, tempW, tempH);

                	        //var dataURL = canvas.toDataURL("image/jpeg");

    	                    var fd = new FormData();

    	                	

    	                    if (opts.csrfToken) {

    	                        fd.append(opts.csrfTokenName, opts.csrfToken);

    	                    }

    	                    var xhr = new XMLHttpRequest();

    	                    xhr.open('POST', opts.uploadUrl, true);

    	                    //xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    	                    //var data = 'image=' + dataURL;

    	                    var FileToCharge = canvas.mozGetAsFile(uploadFileName);

    	                    fd.append(uploadFileName, FileToCharge);

    	                    

    	                    xhr.onload = function () {

    	                        uploadedCount++;

    	                        if (this.status == 200) {

    	                            var resp = JSON.parse(this.response);

    	                            addPhoto(resp['id'], resp['preview'], resp['name'], resp['description'], resp['rank'], resp['translate']/*,resp['model_response']*/);

    	                            ids.push(resp['id']);

    	                        } else {

    	                            // exception !!!

    	                        }

    	                        $uploadProgress.css('width', '' + (5 + 95 * uploadedCount / filesCount) + '%');

    	

    	                        if (uploadedCount === filesCount) {

    	                            $uploadProgress.css('width', '100%');

    	                            $progressOverlay.hide();

    	                            if (opts.hasName || opts.hasDesc) editPhotos(ids);

    	                        }

    	                    };

    	                    xhr.send(fd); 

                	      }

                	 

                	   }

                	   reader.readAsDataURL(file);

                	   /*End Send resized*/

                	} else {

                		// Browser not supported. Try normal file upload

	                	//classic Upload

	                    var fd = new FormData();

	

	                    fd.append(uploadFileName, files[i]);

	                    if (opts.csrfToken) {

	                        fd.append(opts.csrfTokenName, opts.csrfToken);

	                    }

	                    var xhr = new XMLHttpRequest();

	                    xhr.open('POST', opts.uploadUrl, true);

	                    xhr.onload = function () {

	                        uploadedCount++;

	                        if (this.status == 200) {

	                            var resp = JSON.parse(this.response);

	                            addPhoto(resp['id'], resp['preview'], resp['name'], resp['description'], resp['rank'], resp['translate']/*,resp['model_response']*/);

	                            ids.push(resp['id']);

	                        } else {

	                            // exception !!!

	                        }

	                        $uploadProgress.css('width', '' + (5 + 95 * uploadedCount / filesCount) + '%');

	

	                        if (uploadedCount === filesCount) {

	                            $uploadProgress.css('width', '100%');

	                            $progressOverlay.hide();

	                            if (opts.hasName || opts.hasDesc) editPhotos(ids);

	                        }

	                    };

	                    xhr.send(fd);

                	}

                    

                }//end for


            }

Каким образом можно сделать две галереи у одного документа? То есть два galley_id у одного ресурса.

да, и два бихевиора

Yes, but for general case it will require lots changes.

To implement this it will require: XHR2 and FileAPI support (IE 10+), or alternatively this can be done using plugins like flash.

Another problem is image versions descriptions - now it is oriented to work on server side using Image component, and it is hard(and unnecessary, from my point view) to reimplement all this features on client side.

Also one of features of gallery manager is preserving of original image - for possibility to add new image versions in future(it is useful in typical case where I am using this extension).

So, probably this feature will be implemented in some future version that will be almost complete rewrite in comparison to current one(now I am working on a project with some client-side image manipulations).

Any way, if you really need it - fork repository, and add this functionality… If it is required, I can help you with some advice…

In general it would be something similar, but this code have following problems:

  1. downsampling issues when using canvas(more about issue: http://stackoverflow.com/questions/18922880/html5-canvas-resize-downscale-image-high-quality)

  2. you code will work only in FF:


var FileToCharge = canvas.mozGetAsFile(uploadFileName);

see there: https://github.com/blueimp/JavaScript-Canvas-to-Blob

  1. fixed resize dimensions - it would be better to move this into widget options.

  2. Image resizing can take many time, and can cause page to be unresponsive - so you should not process all images at once, you need to use setTimeout to separate image processing and allow browser to handle events from user. (more about: http://stackoverflow.com/questions/672732/prevent-long-running-javascript-from-locking-up-browser)

  3. upload queue and memory management - image manipulation will require not only CPU time, but also memory… So it is not efficient to convert all images and start uploading at once(more over, form my experience - there would be only near five active connections, and due to browser optimisations only few of them would be actively transmitting data). another problem is concurrency with all other ajax calls from you page(they would be required to wait for uploads to finish, in case of the same domain name)… So you need to write upload manager that will sequentially convert and upload images.

Hi,

I installed your extension today, and it really works great! Thanks for your great work!

Is there a way to just view the pictures, without "managing" them? So is there a frontend for the users, which simply display all the images? Or do I have to code it myself using the models and so on?

Thanks and best regards

Daniel

No, this extension is for back-end only.

But I found this cool extension for front-end purposes, which works fantastic and is really easy to install:

http://www.yiiframework.com/extension/magnific-popup/

Actually this is author’s statement on this subject:

[font="Arial Black"]По русски:[/font]

Здравствуй Богдан(тезка))).

Поставил ваше расширение, все по readMe.

Но у меня после загрузки фото у меня ошибка(1)

И ошибка при попытке правки фото(2).

http: //2.firepic.org/2/images/2014-06/23/zyu4c2z0ivl7.jpg

В чем может быть причина этой ошибки?

P.S- Проблема решилась подключением bootstrap.js

[font="Arial Black"]English:[/font]

Hello Bogdan (namesake))).

Put your extension, all at readMe.

But after I download photos from my mistake (1)

And the error when trying to edit photos(2).

http: //2.firepic.org/2/images/2014-06/23/zyu4c2z0ivl7.jpg

P.S-problem solved connecting bootstrap.js

After install all … for make db structure, how can do it, with fast ‘yiic migrate’ command ? thanks ::)

after add a image, firebug get this msg:

"image directory unwritable"

how can fix this? thanks

[solved]

added "/gallery" folder under aplication structure… missed in readme.

thanks

ok after a long time of setting up the code. I got it working somehow and I can see the image gallery on screen!

but i get the following message

Before add photos to product gallery, you need to save product

what shall I do now? pls see attached screenshot

It looks like you are tring to manage gallery of not existing product (model is not saved into database, so there is no gallery because there is no object where to attach it…)

The way how gallery behaviour is working is:

  • on a first save(after behaviour was added to model) it creates gallery, with provided configurations, for a model and saves its id in specified field

  • when you are rendering GalleryManager widged created gallery is used to load initial list of photo and to configure widget

  • after widget is renderd it can be used to manage gallery by "talking" to GalleryController using Id of an gallery

  • when model is deleted from database Gallery behaviour will remove related gallery and all images in it


About your question("what shall I do now?"):

  1. read the documentation, one more time

  2. look an example: https://bitbucket.org/z_bodya/yii-demo-blog

  3. look at extension source code - it is not too complicated, but this would make it much more clear - how extension works

  4. read topics in this thread - I believe, that almost every common issue is covered here.

  5. If you still have questions ask there, but please ask questions that can be answered(if do not understood something concreate, or want to achive something and need an advice, and so on… but not like this one (for me it sounds literally like: "I have done something weird. What shall I do next?")


About you comment on extension page:

http://www.yiiframework.com/extension/imagesgallerymanager/#c18038

Problem why that code is not working, is not about extension… it is because you are not understanding basic concepts how yii framework works: you should not call $this->widget from controller - you should do this in view that should be rendered using CController::render method, othervise widget would not be able to register styles and scripts using Yii::app()->clientScript

Better remove that comment from extension page - it is question, not a comment… it is not about an extension, it is completely useless for anyone…

Taking back all my comments!! Extension works fantastically! Thanks Bogdan

Hi Bogdan

In the controller action of Gallery Controller


/**

     * Method to handle file upload thought XHR2

     * On success returns JSON object with image info.

     * @param $gallery_id string Gallery Id to upload images

     * @throws CHttpException

     */

    public function actionAjaxUpload($gallery_id = null)

    {

        $model = new GalleryPhoto();

        $model->gallery_id = $gallery_id;

        $imageFile = CUploadedFile::getInstanceByName('image');

        $model->file_name = $imageFile->getName();

        $model->save();


        $model->setImage($imageFile->getTempName());

        header("Content-Type: application/json");

        echo CJSON::encode(

            array(

                'id' => $model->id,

                'rank' => $model->rank,

                'name' => (string)$model->name,

                'description' => (string)$model->description,

                'preview' => $model->getPreview(),

            ));

    }



Is the image stored on the server folder under gallery folder?

I checked that the image name is stored in the gallery_photo table but when I checked the gallery folder I see images but they are with different name…

Any idea how to save the images using your extension onto a specific directory in the server?

Image name


$model->file_name

is stored only for purpose of tracking uploaded filenames… it is not used to generate file name on the server or somewhere else…

Actual image is saved there:


$model->setImage($imageFile->getTempName());

Using id from gallery_photo.


Any idea how to save the images using your extension onto a specific directory in the server?

What exactly you want to do? In general you will need to modify extension.

Hello ,

I have read all the instruction steps but still i am unable to understand it please help me how to use this extention as i want to give functionality to create and add gallery imgaes . I am soory for being foolish but still i need to apply this extenion . Urgern :(

I dont understand what do you men by this

1.Checkout source code to your project, for example to ext.galleryManager.

2.Install and configure image component

5.Add GalleryController to application or module controllerMap.

6.Configure and save gallery model

regards,

versha

Юзал галерею для Yii 1, для Yii2 будет?

[size=3]Excuse Me, Sir.[/size]

[size=3] i have any question. for image component extension tar gz after extract, where the folder was placed and what the folder name ?? . Thanks[/size]

Excuse Me, Sir. I have tried the steps that have been given, but when it will be uploaded there was an error. how to handle it ? Help me, please. Thanks

Just finished porting to Yii2.

It is almost ready for use: