Saturday, August 17, 2013

How to pop up the UIImagePickerController in an iphone to select an image?


There are several ways to let the user select an image from a iphone or an ipad. All what we have to do is to use the UIImagePickerController to start the image picking task from the Photo Library, Saved Photos Album and the Camera.
In this post I'm going to explain how to pick an image from the Photo Library. So, make sure that you have images in your photo Library.

Note that you have to tell the program header file (your .h file) that you are using the following delegates

UIApplicationDelegate
UIImagePickerControllerDelegate
UINavigationControllerDelegate

All what you have to do is adding a button on your screen and let the user click on it to start popping up the image picker, let them select an image. If an image is selected successfully, then automatically the delegate method didFinishPickingMediaWithInfo will be called where you can view your image in a UIImageView or do whatever the processing you want with the image.

-(IBAction)selectImage:(id)sender
{
     [self selectAnImage];
}

//method to let the user select an image from the UIImagePickerView
-(void)selectAnImage
{
    ipc=[[UIImagePickerController alloc] init];//instantiate a UIImagePickerViewController object
    ipc.delegate=self;

    //First I am checking that the camera is available
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        NSLog(@"Camera is available");
        ipc.sourceType=UIImagePickerControllerSourceTypeCamera; 
    }
    
    //if not check whether the saved photo album is available
    else if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    {
        NSLog(@"Camera is not available");
        NSLog(@"Photo Album is available");
        
        ipc.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;  
    }
    
    //if none of the above two are avaialble, then use the Photo Library
    else
    {
        NSLog(@"Camera is not available");
        NSLog(@"Photo Album is not available");
        NSLog(@"Photo Library is available");
        
        ipc.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
     [self presentModalViewController:ipc animated:YES];
}

//ImagePickerControler delegate
//triggers when the user has selected an image
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"Test.txt"];
    NSString *temp=[[NSString alloc]initWithString:@"Sample String"];
    [temp writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
      
    //set the selected image
    self.sourceImage=[info objectForKey:UIImagePickerControllerOriginalImage];
    imageDisplay.image=self.sourceImage;    
    [self checkImageResolution:self.sourceImage];
    [[picker parentViewController]dismissModalViewControllerAnimated:YES];
    [picker dismissModalViewControllerAnimated:YES];
}

//ImagePickerControler delegate
//triggers when user did cancel the image selection from the UIimagePickerView
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
  [[picker parentViewController]dismissModalViewControllerAnimated:YES];
}


Thursday, August 15, 2013

How to convert a UIImage to Grayscale?



Please do follow this post along with the post here

Note that I have already shown you the coding on how to pick an image from the UIImagePickerViewController and display it in the UIImageView we have in the screen. So, I assume you have already assigned the selected image's value using imageDisplay.image to the sourceImage variable. 

OK, let's discuss the code to convert an image to Grayscale and display the output.

//this button click even twill call the toGrayscale() method 
-(IBAction) convertGrayScale:(id)sender
{    
    if(sourceImage==nil)//sourceImage  is the user selected image from the Image Picker. I simply display it on a UIImageView and for the processing  i get the image that is currently viewed in the UIImageView
    {
        NSLog(@"Image Not selected");
    }
    
    else
    {   
        UIImage *greyScaledImage=[self toGrayscale:sourceImage];
        resultImageView.image=greyScaledImage;
    } 
}

//method is used to convert an image to its grayscale image and view in the UIImageView on te screen
- (UIImage *) toGrayscale:(UIImage *)initialImage
{
    const int RED = 1;
    const int GREEN = 2;
    const int BLUE = 3;
    
    // Create image rectangle with current image width/height
    CGRect imageRect = CGRectMake(0, 0, initialImage.size.width * initialImage.scale, initialImage.size.height * initialImage.scale);
    
    int width = imageRect.size.width;
    int height = imageRect.size.height;
    
    // the pixels will be painted to this array
    uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));
    
    // clear the pixels so any transparency is preserved
    memset(pixels, 0, width * height * sizeof(uint32_t));
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    // create a context with RGBA pixels
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, 
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
    
    // paint the bitmap to our context which will fill in the pixels array
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [initialImage CGImage]);
    
    for(int y = 0; y < height; y++)
    {
        for(int x = 0; x < width; x++)
        {
            uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
            
            //convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
            
            uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];
            
            // set the pixels to gray
            rgbaPixel[RED] = gray;
            rgbaPixel[GREEN] = gray;
            rgbaPixel[BLUE] = gray;
        }
    }
    
    // create a new CGImageRef from our context with the modified pixels
    CGImageRef image = CGBitmapContextCreateImage(context);
    
    // we're done with the context, color space, and pixels
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    free(pixels);
    
    // make a new UIImage to return
    UIImage *resultUIImage = [UIImage imageWithCGImage:image
                                                 scale:initialImage.scale 
                                           orientation:UIImageOrientationUp];
    
    return resultUIImage;
}


How to re size a UIImage with given height and width?


Please do follow this post along with the post here

here, we allow the user to enter a preferred height and width for the image to be re sized. Once done and click on the re size button, the re sized image will be displayed in the UIImageView below. Following is the implementation

//method to resize the image
//user needs to input the required height and width in the screen
//and cick Resize to apply the resize funtion
-(IBAction) resize:(id)sender
{
    [self.view endEditing:YES];
    
    if(sourceImage==nil)
    {
        NSLog(@"Image Not selected");
    }
        
    else
    { 
        if([getWidth.text isEqualToString:@""] ||  [getHeight.text isEqualToString:@""])
        {
            alert=[[UIAlertView alloc]initWithTitle:@"Image Process" message:@"Height & Width Required" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];   
            
            [alert show];
        }
        
        else
        {            
            CGFloat destinationWidth = [getWidth.text floatValue];
            CGFloat destinationHeight =[getHeight.text floatValue];
            
            CGFloat xOfResultImage = (CGFloat)resultImageView.frame.origin.x;
            CGFloat yOfResultImage = (CGFloat)resultImageView.frame.origin.y;
        
            CGSize passSize=CGSizeMake(destinationWidth, destinationHeight);    
          
            UIImage *resizedImage=[self scaleImage:sourceImage toSize:passSize];
            
            resultImageView.image=resizedImage;
            resultImageView.frame = CGRectMake(xOfResultImage, yOfResultImage,resizedImage.size.width, resizedImage.size.height);
            
        }
    }
}

//to scale images without changing aspect ratio
- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize
{
    float width = newSize.width;
    float height = newSize.height;
    
    UIGraphicsBeginImageContext(newSize);
    CGRect rect = CGRectMake(0, 0, width, height);
    
    float widthRatio = image.size.width / width;
    float heightRatio = image.size.height / height;
    float divisor = widthRatio > heightRatio ? widthRatio : heightRatio;
    
    width = image.size.width / divisor;
    height = image.size.height / divisor;
    
    rect.size.width  = width;
    rect.size.height = height;
    
    //indent in case of width or height difference
    float offset = (width - height) / 2;
    
    if (offset > 0)
    {
        rect.origin.y = offset;
    }
    else
    {
        rect.origin.x = -offset;
    }
    
    [image drawInRect: rect];
    
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage ;   
}


Friday, May 3, 2013

Creating a colorful Animation in CSS3

Creating animation using few steps in an easier manner is no more magic with CSS3. It's really simple to create CSS3 animations which can even be replaced for animated images, flash animations and JavaScript in web pages.  

Before going through this post about animations, I prefer if you can go through the couple of previous psost on CSS3 2D and 3D transforms that I have published. Most of the concepts used their will be helpful in understanding this post. 

First of all, to create animation in CSS3, we have to know about a stranger and that is key-frame  If you know some animation creating tool like flash, Moho or even any video editing tools, you will surely know what these key frames are. Yes, collection of key frames makes a complete animation. here, in CSS3, the rule is @keyframes and it is where the animation is created. We have to specify a CSS style inside the @keyframes rule and the animation will gradually change from the current style to the new style.

Note that, I use Google Chrome to test all my HTML5 and CSS3 pages throughout all these posts where Chrome requires the prefix -webkit- to work with them. 

When the animation is created in the @keyframe, bind it to a selector, otherwise the animation will have no effect.

Bind the animation to a selector by specifying at least these two CSS3 animation properties:
-->Specify the name of the animation
-->Specify the duration of the animation

It's just like creating a keyframe and telling who should use it specifying a time as well. So, all we have to do is creating @keyframes specifying when each of them should be displayed  and what will be changed in the element during the appearance of each of those key frames and finally telling the element which required the animation in it about the key frames we have created.

I thought to go for a little animation example at once, without describing little concepts that you may already know.

first of all, I would like you to see the output by following the link below to know what we are going to animate.




Don't get scared :) you have to do very little work in CSS3 to get that output. have a look at the code below.

<!DOCTYPE html>
<html>
<head>
<style> 

/*I am just creating a div with some styles as below
then i also specfy that it is going  to be animated using the myfirst @keyframes
 */
div
{
width:150px;
height:150px;
border-style:ridge;
border-radius:20px;
background:red;
position:relative;

-webkit-animation:myfirst 15s; /*the animation using myfirst keyframes will last for 15 seconds*/
}

/*now, we'll create the @keyframes
Note that, I want to move my div element to ten diffrrent position in ten diffrrent colors
so, I specify the starting (0%) and ending (100%) points with  a collection of gradually increasing percentage values to get hold of ten positions. 
In each position , I specify a new color to the background and state the x and y positions where the div should find its path through. The path I specify is sort of a box-zig-zag way.
Do a little calculation to decide the x and y positions that you must follow, then it's a matter of applying the same in each line :) that's all with CSS3. then you can use the div tag wherever you want in the page.
the animation is done ...
[the highlighted part does a small transform to rotate the element around X axis to 360 degrees as a 3D transformation]
*/

@-webkit-keyframes myfirst
{
0%   {background:aqua; left:0px; top:0px;-webkit-transform:rotateX(360deg)}
10%  {background:blue; left:0px; top:100px;}
20%  {background:cyan; left:100px; top:100px;}
30%  {background:green; left:100px; top:0px;}
40%  {background:pink; left:200px; top:0px;}
50%  {background:purple; left:200px; top:100px;}
60%  {background:magenta; left:300px; top:100px;}
70%  {background:coral; left:300px; top:0px;}
80%  {background:red; left:300px; top:0px;}
90%  {background:orange; left:300px; top:100px;}
100% {background:yellow; left:400px; top:100px;}
}
</style>
</head>
<body>

<p>This shape changes ten positions in ten different colors</p>

<div>@@@@@@@@@@</div>

</body>
</html>






How to do a simple 3D Transform in CSS3?

In my previous post, I have described how to perform simple 2D transforms with some examples. Here I am going to describe a similar thing but here, our shape is going to transform it self in a 3D surface. have a look at the below output. shape mentioned as 'I am Happy' rotates around X axis to 360 degrees and shape 'I am sad' rotates around Y axis to 360 degrees within 7 minutes changing their colors. this happens once the user hovers over the shapes.




It's not that complex. You should know to apply styles to a simple div control to design the above shape. Little knowledge on how 2D transform happens in CSS3. All what have done above is to let the two shapes rotate in X axis and Y axis to 360 degrees once the user hovers on them. Meanwhile it changes the colors and all it happens within 7 seconds. observe the code below. since the code is simple enough to handle in the same file, i have not used an external style sheet to include the style tag.

<!DOCTYPE html>
<html>
<head>
<title>3D Transitions</title>
<style>

/*creates the initial div tag and two of its properties (background and transform defines time for transformations)*/
div
{
width:200px;
height:200px;
background:cyan;
border-radius:10px;
border-style:dotted;
font:40px Verdana;
-webkit-transition: background 7S,-webkit-transform 7S;
}

/*once the use hovers over div element, transform rotate it over 360 degrees in X axis during 7 minuets*/
div:hover
{
-webkit-transform:rotateX(360deg);
background:Orange;
} /*get all the features of div to div2 and once the use hovers over div2 element, transform rotate it over 360 degrees in Y axis during 7 minuets*/
div#div2:hover
{
-webkit-transform:rotateY(360deg);
background:purple;
}
</style>
<!-------------------------------------------------------------->
</head>
<body>
<div >I am Happy :) </div>
<br/>
<div id="div2">I am Sad :( </div>
</body>
</html>

that's all you have to do.





Thursday, May 2, 2013

Trying different types of Transitions in CSS3



This is another wonderful feature that I found in CSS3. Now, we can make small animations and transitions with the help of just CSS3 but without using flash or any other tool support. CSS3 allows adding effect when changing from one style to another. for an example, you can see some element increases its height within 5 seconds of time when you hover over it. even you can apply multiple transition effects to the same element at the same time. You will definitely enjoy trying out these examples under this post.

First of all, I don't like to bore you with coding but this time, I would like you to examine the output first. Do click the following link to view the output in the browser itself (please make sure that your browser supports all these features of HTM5 and CSS3)


OK, now let's go through the concept behind it. CSS3 transitions are effects that let an element gradually change from one style to another. To do this, you must specify two main things;


  1. Specify the CSS property you want to add an effect to (e.g :- height)
  2. Specify the duration of the effect (e.g:- within 5 seconds)
if you did not specify a time duration to apply the effect, the transition wont take place since the default value for time is considered to be 0. The effect will start when the specified CSS property changes value. A typical CSS property change would be when a user mouse-over an element:

Throughout this post, I'll explain, transitions that take place when you hover over a div element.

change color from magenta to cyan within 5 seconds when hovered over


.div1
{
width:100px;
height:100px;
border-style:dashed;
background:magenta;
border-radius:50px;

-webkit-transition:background 5s;          /*says to make a transition in background within 5 seconds*/
}

.div1:hover                     /*says when you hover over div1 class elements, change the background to cyan*/
{
background:cyan;
}

change the height to 200px within 3 seconds when hovered


.div2
{
width:100px;
height:100px;
background:blue;
border-radius:10px;

-webkit-transition:height 3s;
}

.div2:hover
{
height:200px;
}

change the width to 50px within 5 seconds when hovered and transit the color to orange


.div3
{
width:200px;
height:100px;
background:pink;
border-radius:10px;

-webkit-transition:width 5s,background 5s;

}

.div3:hover
{
width:100px;
background:orange;
}

Performing multiple transitions


/*once hovered, do the following
    change the color from green to blue
    increase the width from 100px to 150px
    increase the height from 100 px to 150 px
    rotate the shape 360 degrees
    do all of the above within 7 seconds
*/

.div4
{
width:100px;
height:100px;
background:cyan;
border-color:Blue;
border-bottom-style:solid;
border-radius:50px;
-webkit-transition:width 7s,height 7s,background 7s, -webkit-transform 7s, border-color 7s;

}

.div4:hover
{
width:150px;
height:150px;
background:blue;
border-color:cyan;
-webkit-transform:rotate(360deg);
}

following code shows how you need to use these div elements in your html page


    <h3>
    Hover over me, I change my color :)
    </h3>

    <div class=div1></div>

    <h3>
    Hover over me, my height increases
    </h3>
    <div class=div2></div>

    <h3>
    Hover over me, my width increases and color changes
    </h3>
    <div class=div3></div>

    <h3>
    Hover over me, I make lot of transitions
    </h3>
    <div class=div4></div>




2D Transforms in CSS3

Cascading Style Sheets or simply CSS is used to control the style and layout of Web pages. Css3 has been introduced with lot of improved features than that were there in earlier versions of CSS3. CSS3 allows users to create 2D Transforms, 3D Transforms  Transitions, Animation and so many more colorful and interesting features to be added to the web pages that they create. Through these features, we b pages improve their performance much more other than using videos or something like flash controls to create attractive web designs.

I am going to describe some interesting 2D Transforms that are available in CSS3. All what I am going to play around here is a simple div control with some initial styles. It will be used through out all the steps to demonstrate different 2D Transforms. A Transform is an effect that lets an element change shape, size and position.

Though I can embed the style tags within my html page, I have created them seperately, but I'll be explaining each together for clarification.

OK, this is my initial div with styles

//in StyleSheet2.css file
div
{
   width:100px;
   height: 75px;
   border:5px;
   border-style:ridge;
   border-radius:7px;
   background-color:Aqua; 
}


//in Css3Transform.html file
<div class="div"> I am the original div</div>

output:-







I am going to shift the shape 50px in X axis and 100px in Y axis


//in StyleSheet2.css file
div#div2
{
    background-color:Coral;       
    -webkit-transform:translate(200px,30px);/*move the div 200px of X and 30px of Y*/
}

//in Css3Transform.html file

<div id="div2">I am translated by 50px of x and 100px of y</div>

I am going to rotate the shape by 30 degrees


//in StyleSheet2.css file

div#div3

  background-color:CornflowerBlue;       
 -webkit-transform:rotate(30deg); /* rotate the above div in 30 degrees(works in Chrome) */  
}

//in Css3Transform.html file

<div id="div3"> I am rotated by 30 degrees</div>

I am going to scale up the shape by 1.5 times of x and 2 times of Y


//in StyleSheet2.css file
div#div4
{
    background-color:Aquamarine;
    -webkit-transform:scale(1.5,2);/*scale up x with 1.5 times and y with 2 times*/
}

//in Css3Transform.html file

<div id="div4"> i am scaled up 1.2 times x and 1.5 times y</div>

I am going to turn the shape 20 degrees to X axis and 30 degrees to Y axis


//in StyleSheet2.css file
div#div5
{
    background-color:BurlyWood;
    -webkit-transform:skew(20deg,30deg);
    /*With the skew() method, the element turns in a given angle, 
    depending on the parameters given for the horizontal (X-axis) 
    and the vertical (Y-axis) lines:*/
}

//in Css3Transform.html file

<div id="div5"> i am skewed 20deg to X and 30degs to Y</div>


I am going to turn the shape only toward X axis by 45 degrees


//in StyleSheet2.css file
div#div6
{
    background-color:Purple;
    -webkit-transform:skewX(45deg);/*turn to X axis only in 45 degrees */
}

//in Css3Transform.html file

<div id="div6"> i am skewed 45deg to X only</div>


I am going to turn the shape only toward Y axis by 45 degrees



//in StyleSheet2.css file
div#div7
{
    background-color:Pink;
    -webkit-transform:skewY(45deg);/*turn to y axis only in 45 degrees */
}


//in Css3Transform.html file
<div id="div7"> i am skewed 45deg to Y only</div>


The final output compared to the initial div element:-

you can get the source files from the below links

DOWNLOAD FROM HERE


VIEW IN BROWSER