Steven
Steven

Reputation: 11

Rotate and save image in Titanium?

I am currently working on an android app that allow user to rotate the image then save it. I am able to save the image but when I check it, it doesn't rotate. Would appreciate if someone can point me to a right direction.

Here is my code:

_rotateLeft.addEventListener('click', function(e){
            _rotationDegree = _rotationDegree - 90;
            var t = Ti.UI.create2DMatrix();
            //t.rotate(90);
            //imageContainer.transform = t;

            imageContainer.animate({
                transform: t.rotate(_rotationDegree)
            });
        });

_saveButton.addEventListener('click', function(){
    var imgSave = imageView.toImage();
    var moment          = require('alloy/moment');

    var directory = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, 'images/test');
    !directory.exists() && directory.createDirectory();

    var fileName        = String.format('rotate_%s.jpg', moment().format('YYYY-MM-DD-HH-mm'));
    var file            = Ti.Filesystem.getFile(directory.resolve(), fileName);
    var fileNativePath  = file.nativePath;
    // Write media to file
    //file.write(newBlob);
    file.write(imgSave);

    Ti.API.info('New Save File : ' + JSON.stringify(file));

    imageView.setImage(file);

});

Here is my view:

<View id="imageContainer">
        <!--<View id="imageUploadedView"></View>-->
        <ImageView id="imageView"></ImageView>
    </View>

Upvotes: 0

Views: 713

Answers (2)

Marchief
Marchief

Reputation: 81

You need to declare the transform first then apply the transform to the view before saving.

_rotateLeft.addEventListener('click', function(e){
  var rotateTransform = Ti.UI.create2DMatrix({ 
  rotate: 45 
  });

imageContainer.transform = rotateTransform;
}

Reference: http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.2DMatrix

Upvotes: 0

Prashant Saini
Prashant Saini

Reputation: 3539

There are 2 things I found odd in your code:

1 - You are rotating imageContainer and then you are capturing imageView.toImage(); which I think is the cause of issue because:

  • Rotating container view rotates the child elements also, and capturing a child.toImage(); will return you the UI of that child irrespective of the rotation (though I am not 100% sure because I would prefer below step to do this task).
  • So to make to properly work, rotate imageView and use imageContainer.toImage(); so that child view is rotated and parent view can save its rotated state.

2 - Inside _saveButton click event, use this line: imageView.setImage(file.read()); because you were not reading the blob data of the file in your code.

Upvotes: 1

Related Questions