Latest Entries »

Image Files Manage

– (void)saveImage:(UIImage*)image:(NSString*)imageName {

NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.

NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it

NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@”%@”, imageName]]; //add our image to the path

[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)

NSLog(@”image saved”);

}

//removing an image

– (void)removeImage:(NSString*)fileName {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@”%@”, fileName]];

[fileManager removeItemAtPath: fullPath error:NULL];

NSLog(@”image removed”);

}

– (void)RemoveAllFile
{
NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *all = [fileManager directoryContentsAtPath: documentsDirectory];

for (int i=0;i<[all count];i++) {
NSString *fileName = [[NSString alloc] initWithFormat:@”%@”,[all objectAtIndex:i]];
[self removeImage:fileName];
}
}
}

//loading an image

– (UIImage*)loadImage:(NSString*)imageName {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@”%@”, imageName]];

return [UIImage imageWithContentsOfFile:fullPath];

}

Advertisements

UIImage *imageData = [UIImage alloc];

NSData *DataOfImage = UIImageJPEGRepresentation(imageData, 1.0);
NSString *encodedString = [DataOfImage base64Encoding];

[self performSelectorOnMainThread:@selector(didLoadImageInBackground:) withObject:image waitUntilDone:YES];

 

– (void)didLoadImageInBackground:(UIImage *)image {
[currentImage setImage: image];
}

 

-(BOOL)IsInternateAvailable
{
Reachability* internetReachable;
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];

NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];

switch (internetStatus)
{
case NotReachable:
{
NSLog(@”The internet is down.”);
return NO;
}
}

return YES;
}

– (UIImage *)scaleAndRotateImage:(UIImage *)image
{
int kMaxResolution = 320; // Or whatever

CGImageRef imgRef = image.CGImage;

CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);

CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
if (width > kMaxResolution || height > kMaxResolution) {
CGFloat ratio = width/height;
if (ratio > 1) {
bounds.size.width = kMaxResolution;
bounds.size.height = bounds.size.width / ratio;
}
else {
bounds.size.height = kMaxResolution;
bounds.size.width = bounds.size.height * ratio;
}
}

CGFloat scaleRatio = bounds.size.width / width;
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = image.imageOrientation;
switch(orient) {

case UIImageOrientationUp: //EXIF = 1
transform = CGAffineTransformIdentity;
break;

case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;

case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;

case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;

case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;

case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;

default:
[NSException raise:NSInternalInconsistencyException format:@”Invalid image orientation”];

}

UIGraphicsBeginImageContext(bounds.size);

CGContextRef context = UIGraphicsGetCurrentContext();

if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
CGContextScaleCTM(context, -scaleRatio, scaleRatio);
CGContextTranslateCTM(context, -height, 0);
}
else {
CGContextScaleCTM(context, scaleRatio, -scaleRatio);
CGContextTranslateCTM(context, 0, -height);
}

CGContextConcatCTM(context, transform);

CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return imageCopy;
}

– (void)didLoadImageInBackground:(UIImage *)image {

[currentImage setImage: image];

CGFloat totalWidth = self.view.frame.size.width;
CGFloat totalHeight = self.view.frame.size.height;

CGImageRef imgRef = image.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);

if(width>totalWidth)
{
height = (height * totalWidth) / width;
width = totalWidth;
}

if(height > totalHeight)
{
width = (width * totalHeight) / height;
height = totalHeight;
}

[currentImage setFrame:CGRectMake(0, 0, width, height)];
currentImage.center = CGPointMake(totalWidth/2, self.view.center.y);
}

-(CLLocationCoordinate2D) addressLocation:(NSString *)address {
NSString *urlString = [NSString stringWithFormat:@”http://maps.google.com/maps/geo?q=%@&output=csv&#8221;,
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:@”,”];

double _latitude = 0.0;
double _longitude = 0.0;

if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@”200″]) {
_latitude = [[listItems objectAtIndex:2] doubleValue];
_longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D _location;
_location.latitude = _latitude;
_location.longitude = _longitude;

//NSLog(@”%f – %f”, latitude, longitude);

return _location;
}

public static class StringExtension
{
private static readonly Regex WebUrlExpression = new Regex(@”(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?”, RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex EmailExpression = new Regex(@”^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$”, RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex StripHTMLExpression = new Regex(“<\\S[^><]*>”, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex AlphaNumericExpression = new Regex(@”^[a-zA-Z0-9]*$”, RegexOptions.Singleline | RegexOptions.Compiled);

private static readonly char[] IllegalUrlCharacters = new[] { ‘;’, ‘/’, ‘\\’, ‘?’, ‘:’, ‘@’, ‘&’, ‘=’, ‘+’, ‘$’, ‘,’, ‘<‘, ‘>’, ‘#’, ‘%’, ‘.’, ‘!’, ‘*’, ‘\”, ‘”‘, ‘(‘, ‘)’, ‘[‘, ‘]’, ‘{‘, ‘}’, ‘|’, ‘^’, ‘`’, ‘~’, ‘–’, ‘‘’, ‘’’, ‘“’, ‘”’, ‘»’, ‘«’ };

[DebuggerStepThrough]
public static bool IsAlphaNumeric(this string target)
{
return !string.IsNullOrEmpty(target) && AlphaNumericExpression.IsMatch(target);
}

[DebuggerStepThrough]
public static bool IsPhoneNumber(this string target)
{
return !string.IsNullOrEmpty(target.Trim()) && target.Replace(” “, “”).ToCharArray().All(x => char.IsDigit(x) || x == ‘-‘ || x == ‘(‘ || x == ‘)’);
}

[DebuggerStepThrough]
public static bool IsWebUrl(this string target)
{
return !string.IsNullOrEmpty(target) && WebUrlExpression.IsMatch(target);
}

[DebuggerStepThrough]
public static bool IsEmail(this string target)
{
return !string.IsNullOrEmpty(target) && EmailExpression.IsMatch(target);
}

[DebuggerStepThrough]
public static bool IsNullOrEmpty(this string target)
{
return string.IsNullOrEmpty(target);
}

[DebuggerStepThrough]
public static bool IsNotNullOrEmpty(this string target)
{
return !string.IsNullOrEmpty(target);
}

[DebuggerStepThrough]
public static string NullSafe(this string target)
{
return (target ?? string.Empty).Trim();
}

[DebuggerStepThrough]
public static string StripHtml(this string target)
{
return StripHTMLExpression.Replace(target, string.Empty);
}

[DebuggerStepThrough]
public static Guid ToGuid(this string target)
{
Guid result = Guid.Empty;

if ((!string.IsNullOrEmpty(target)) && (target.Trim().Length == 22))
{
string encoded = string.Concat(target.Trim().Replace(“-“, “+”).Replace(“_”, “/”), “==”);

try
{
byte[] base64 = Convert.FromBase64String(encoded);

result = new Guid(base64);
}
catch (FormatException)
{
}
}

return result;
}

[DebuggerStepThrough]
public static string ToLegalUrl(this string target)
{
if (string.IsNullOrEmpty(target))
{
return target;
}

target = target.Trim();

if (target.IndexOfAny(IllegalUrlCharacters) > -1)
{
foreach (char character in IllegalUrlCharacters)
{
target = target.Replace(character.ToString(CultureInfo.CurrentCulture), string.Empty);
}
}

target = target.Replace(” “, “-“);

while (target.Contains(“–“))
{
target = target.Replace(“–“, “-“);
}

return target;
}

[DebuggerStepThrough]
public static string UrlEncode(this string target)
{
return HttpUtility.UrlEncode(target);
}

[DebuggerStepThrough]
public static string UrlDecode(this string target)
{
return HttpUtility.UrlDecode(target);
}

[DebuggerStepThrough]
public static string AttributeEncode(this string target)
{
return HttpUtility.HtmlAttributeEncode(target);
}

[DebuggerStepThrough]
public static string HtmlEncode(this string target)
{
return HttpUtility.HtmlEncode(target);
}

[DebuggerStepThrough]
public static string HtmlDecode(this string target)
{
return HttpUtility.HtmlDecode(target);
}

public static string Replace(this string target, ICollection<string> oldValues, string newValue)
{
oldValues.ForEach(oldValue => target = target.Replace(oldValue, newValue));
return target;
}

public static string SafeSubString(this string target, int startIndex, int length)
{
return startIndex + length > target.Length ? target.Substring(startIndex, target.Length) : target.Substring(startIndex, length);
}
}

public static string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();

// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}

public static Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}

Image Resize

public static Bitmap ReSizeBitmap(Bitmap btp, int width, int height)
{
int originalW = btp.Width;
int originalH = btp.Height;
int proportionsW = 0;
int proportionsH = 0;

if ((originalH * width) / originalW <= height)
{
proportionsW = width;
proportionsH = (originalH * width) / originalW;
}
else
{
proportionsH = height;
proportionsW = (originalW * height) / originalH;
}

Bitmap bmp = new Bitmap(width, height);

//create a new graphic from the Bitmap
Graphics graphic = Graphics.FromImage((Image)bmp);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
//draw the newly resized image
graphic.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, width, height));
graphic.DrawImage(btp as Image, (width – proportionsW) / 2, (height – proportionsH) / 2, proportionsW, proportionsH);
graphic.Dispose();
//return the image
return bmp;
}