How to display .RGB on uiimageview - ios4

I am having file with extension .RGB and need to display it on uiimageview.
For this i need to convert the .RGB format to specific format like .PNG or .JPEG however unable to get it right .
I tried with following code for this.
UIImage *image=[UIImage imageNamed:#"Attachment.RGB"];
CGImageRef imageRef=[image CGImage];
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
NSData *pngData = UIImagePNGRepresentation(myImage);
UIImage* imageFinal = [UIImage imageWithData:pngData];
image_view.image=imageFinal;
There are online websites which can convert the RGB to visible image .But i didn't found any solution for objective c .
Can any one help me on this .
Regards
Pagyyy123

You can use the readtex.c for this which is open source implementations for this.. see the sample following code snippets...
static TK_RGBImageRec *tkRGBImageLoad(const char *fileName)
{
rawImageRec *raw;
TK_RGBImageRec *final;
raw = RawImageOpen(fileName);
if (!raw) {
fprintf(stderr, "File not found\n");
return NULL;
}
final = (TK_RGBImageRec *)malloc(sizeof(TK_RGBImageRec));
if (final == NULL) {
fprintf(stderr, "Out of memory!\n");
return NULL;
}
final->sizeX = raw->sizeX;
final->sizeY = raw->sizeY;
final->components = raw->sizeZ;
RawImageGetData(raw, final);
RawImageClose(raw);
return final;
}
http://opensource.apple.com/source/X11server/X11server-85/mesa/Mesa-7.2/progs/util/readtex.c
I hope the above URL will help.

Related

"Adjust to fit" causes memory leak for UITextField category (or subclass)

When using a category on UITextField, the "Adjust to fit" and minimum font size options may cause a memory leak, when text inside such a field exceeds its visible boundaries. I tried subclassing instead, but it did not solve the problem.
Here is how my category implementation looks like:
#implementation UITextField (custom)
static NSString *fontName = #"My-Awsome-Font";
static UIColor *color;
static UIFont *smallFont;
static UIFont *largeFont;
static NSDictionary *smallAttributes;
static NSDictionary *largeAttributes;
static NSString *placeholder;
static bool shouldModifyPlaceholder;
- (CGRect)textRectForBounds:(CGRect)bounds
{
if(largeFont == nil)
largeFont = [UIFont fontWithName:fontName size:20.0];
if(smallFont == nil)
smallFont = [UIFont fontWithName:fontName size:16.0];
if(smallAttributes == nil)
smallAttributes = #{NSFontAttributeName: smallFont};
if(largeAttributes == nil)
largeAttributes = #{NSFontAttributeName: largeFont};
// general elements
[self setBackgroundColor:[UIColor whiteColor]];
[self.layer setBorderColor:[UIColor whiteColor].CGColor];
[self.layer setBorderWidth:2.0];
self.font = largeFont;
self.layer.cornerRadius = 3;
self.clipsToBounds = YES;
//
shouldModifyPlaceholder = [self respondsToSelector:#selector(setAttributedPlaceholder:)] && ![placeholder isEqualToString:self.placeholder];
// custom elements for each size category
if (self.frame.size.width <= 90) {
if (shouldModifyPlaceholder) {
if ([self.placeholder length] > 3) {
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:smallAttributes];
}
else {
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:largeAttributes];
}
placeholder = self.placeholder;
}
return CGRectMake(bounds.origin.x + 18, bounds.origin.y + 9,
bounds.size.width - 36, bounds.size.height - 16);
}
else {
if (shouldModifyPlaceholder) {
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:largeAttributes];
placeholder = self.placeholder;
}
return CGRectMake(bounds.origin.x + 20, bounds.origin.y + 9,
bounds.size.width - 40, bounds.size.height - 16);
}
}
Recently I discovered that typing "too much" text into a UITextField caused my app to use up all the phone's memory and crash. I found out that it was due to the fact that my customisation did not work well with the "Adjust to fit" option. Removing "Adjust to fit" fixed the issue. I also set minimum font size property to the original font size to be sure. And since I used well over a day trying to find a solution, I thought I'd share this in case someone else runs into this problem.

Image getting zoomed and cut off when converting from binary data

I have some background images stored as binary data. I need to draw something on it based on data and then show it as a single image in the browser. The issue is that some of the images are getting zoomed in and some get zoomed out when I try to do this with the following code. Can anyone please tell where I am going wrong?
int imageWidth = 0, imageHeight=0;
Image bmpImg;
if (datatable.Rows.Count > 0)
{
bmpImg = Bitmap.FromStream(new MemoryStream((byte[])datatable.Rows[0]["data"]));
imageWidth = bmpImg.Width;
imageHeight= bmpImg.Height;
}
else{
bmpImg = null;
}
bitmap = new Bitmap(imageWidth, imageHeight);
//bitmap = new Bitmap(1000, 800);
renderer = SvgRenderer.FromImage(bitmap);
graphics = Graphics.FromImage(bitmap);
if(bmpImg != null)
{
graphics.DrawImage(bmpImg, 0, 0);
}
//perform other drawings using graphics
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Png);
bitmap.Dispose();
renderer.Dispose();
After some searching, I got the answer from another question : Graphics.DrawImage unexpectedly resizing image
Basically you have to change this:
graphics.DrawImage(bmpImg, 0, 0);
to
graphics.DrawImage(bmpImg,new Rectangle(0,0,imageWidth,imageHeight));

How to use NSCache with CoreData

I have developed a project, where a user draws a image on a canvas, I store it in the file using CoreData, I have one-to-many relationship called folder-to-files. So here all are images. I retrive the images from files , resize according to my table cell height and show it on a table. Once it is shown, I want to cache the images.
I also have some labels on the folder cell, which give me some info regarding my files, which I update on fly.
I also swipe the cells to mark it complete and move it to the bottom the cell.
I also show same file images in different Views depending on how user queries it.
I want to know the best method for this, I read through the web, their are many methods, GCD, NSOperationQueues and many more.
Which method will be best suited for me.
I want to show some code
- (UITableViewCell *)tableView:(FMMoveTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
FolderCell *tableCell = (FolderCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (tableCell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"FolderCell" owner:self options:nil];
tableCell = [nib objectAtIndex:0];
}
NSMutableArray *categoryArray = [[self.controller fetchedObjects]mutableCopy];
Folder *category = [categoryArray objectAtIndex:[indexPath row]];
[tableCell configureCellWithNote:category]; //This function is written in my FolderCell.m function
}
return tableCell;
}
-(void)configureCellWithNote:(Folder *)category
{
self.category = category;
UIImage *image1 = [UIImage imageWithData:category.noteImage];
CGSize newSize;
if(image1.size.width == 620 && image1.size.height == 200)
{
newSize = CGSizeMake(300, 97);
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image1 drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.notesImage.image = newImage;
}
So what is happening here is that configureCellWithNote is taking lot of time, because it is resizing images. Please help me out in deciding how can this performance issue be solved.
Regards
Rajit
If you simply want to shuffle the resize operation to a background thread, you could do something like this:
- (void)configureCellWithNote:(Folder *)category
{
self.category = category;
UIImage *image1 = [UIImage imageWithData:category.noteImage];
CGSize newSize;
if(image1.size.width == 620 && image1.size.height == 200)
{
newSize = CGSizeMake(300, 97);
}
dispatch_async(dispatch_get_global_queue(0,0), ^{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image1 drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
self.notesImage.image = newImage;
});
});
}
If you want to cache the results, then the trick will be to come up with a good cache key. Unfortunately, it's hard to tell from what you've posted what would make a good cache key. Certainly it will need to include the size, but it'll also need to include something that ties it back to the category. I suppose if nothing else you could use the NSManagedObjectID for the category, but I think that'll be specific to each managed object context you have. Assuming there was a property on Folder called uniqueName a caching implementation might look like this:
- (UIImage*)imageForCategory: (Folder*)category atSize: (CGSize)size
{
// A shared (i.e. global, but scoped to this function) cache
static NSCache* imageCache = nil;
// The following initializes the cache once, and only once
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
imageCache = [[NSCache alloc] init];
});
// Generate a cache key sufficient to uniquely identify the image we're looking for
NSString* cacheKey = [NSString stringWithFormat: #"%#|%#", category.uniqueName, NSStringFromSize((NSSize)size)];
// Try fetching any existing image for that key from the cache.
UIImage* img = [imageCache objectForKey: cacheKey];
// If we don't find a pre-existing one, create one
if (!img)
{
// Your original code for creating a resized image...
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
UIImage* image1 = [UIImage imageWithData:category.noteImage];
[image1 drawInRect:CGRectMake(0,0,size.width,size.height)];
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Now add the newly-created image to the cache
[imageCache setObject: img forKey: cacheKey];
}
// Return the image
return img;
}

Convert WebView to PDF

I'm trying to take a WebView and convert it to a PDF. I've got the code working to convert the view to an image but would rather have a PDF.
public void ConvertToPDF(UIWebView webView)
{
RectangleF canvasRect = view.Bounds;
CGPDFInfo info = new CGPDFInfo();
info.AllowsPrinting = true;
UIGraphics.BeginPDFContext (Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.Personal),"MyDocument.PDF"), canvasRect, info);
UIGraphics.BeginPDFPage ();
CGContext gctx = UIGraphics.GetCurrentContext ();
view.Layer.RenderInContext (ctx);
UIGraphics.EndPDFContent ();
}
All I get with above code is a blank pdf.
Thanks,
Rick
CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, 1);
UIImage *pageImage = [PDFPageConverter convertPDFPageToImage:page withResolution:144];
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:destinationPath];
[UIImagePNGRepresentation(pageImage) writeToFile:pngPath atomically:YES];
this code will do the stuffs
just pass CGPDFDocument object and page number to function
or
download example from below link
http://ipdfdev.com/2011/04/22/convert-an-image-to-pdf-on-the-iphone-and-ipad/

Blackberry - how to resize image?

I wanted to know if we can resize an image. Suppose if we want to draw an image of 200x200 actual size with a size of 100 x 100 size on our blackberry screen.
Thanks
You can do this pretty simply using the EncodedImage.scaleImage32() method. You'll need to provide it with the factors by which you want to scale the width and height (as a Fixed32).
Here's some sample code which determines the scale factor for the width and height by dividing the original image size by the desired size, using RIM's Fixed32 class.
public static EncodedImage resizeImage(EncodedImage image, int newWidth, int newHeight) {
int scaleFactorX = Fixed32.div(Fixed32.toFP(image.getWidth()), Fixed32.toFP(newWidth));
int scaleFactorY = Fixed32.div(Fixed32.toFP(image.getHeight()), Fixed32.toFP(newHeight));
return image.scaleImage32(scaleFactorX, scaleFactorY);
}
If you're lucky enough to be developer for OS 5.0, Marc posted a link to the new APIs that are a lot clearer and more versatile than the one I described above. For example:
public static Bitmap resizeImage(Bitmap originalImage, int newWidth, int newHeight) {
Bitmap newImage = new Bitmap(newWidth, newHeight);
originalImage.scaleInto(newImage, Bitmap.FILTER_BILINEAR, Bitmap.SCALE_TO_FILL);
return newImage;
}
(Naturally you can substitute the filter/scaling options based on your needs.)
Just an alternative:
BlackBerry - draw image on the screen
BlackBerry - image 3D transform
I'm not a Blackberry programmer, but I believe some of these links will help you out:
Image Resizing Article
Resizing a Bitmap on the Blackberry
Blackberry Image Scaling Question
Keep in mind that the default image scaling done by BlackBerry is quite primitive and generally doesn't look very good. If you are building for 5.0 there is a new API to do much better image scaling using filters such as bilinear or Lanczos.
For BlackBerry JDE 5.0 or later, you can use the scaleInto API.
in this there is two bitmap.temp is holding the old bitmap.In this method you just pass
bitmap ,width,height.it return new bitmap of your choice.
Bitmap ImgResizer(Bitmap bitmap , int width , int height){
Bitmap temp=new Bitmap(width,height);
Bitmap resized_Bitmap = bitmap;
temp.createAlpha(Bitmap.HOURGLASS);
resized_Bitmap.scaleInto(temp , Bitmap.FILTER_LANCZOS);
return temp;
}
Here is the function or you can say method to resize image, use it as you want :
int olddWidth;
int olddHeight;
int dispplayWidth;
int dispplayHeight;
EncodedImage ei2 = EncodedImage.getEncodedImageResource("add2.png");
olddWidth = ei2.getWidth();
olddHeight = ei2.getHeight();
dispplayWidth = 40;\\here pass the width u want in pixels
dispplayHeight = 80;\\here pass the height u want in pixels again
int numeerator = net.rim.device.api.math.Fixed32.toFP(olddWidth);
int denoominator = net.rim.device.api.math.Fixed32.toFP(dispplayWidth);
int widtthScale = net.rim.device.api.math.Fixed32.div(numeerator, denoominator);
numeerator = net.rim.device.api.math.Fixed32.toFP(olddHeight);
denoominator = net.rim.device.api.math.Fixed32.toFP(dispplayHeight);
int heighhtScale = net.rim.device.api.math.Fixed32.div(numeerator, denoominator);
EncodedImage newEi2 = ei2.scaleImage32(widtthScale, heighhtScale);
Bitmap _add =newEi2.getBitmap();
I am posting this answers for newbie in Blackberry Application development. Below code is for processing Bitmap images from URL and Resizing them without loass of Aspect Ratio :
public static Bitmap imageFromServer(String url)
{
Bitmap bitmp = null;
try{
HttpConnection fcon = (HttpConnection)Connector.open(url);
int rc = fcon.getResponseCode();
if(rc!=HttpConnection.HTTP_OK)
{
throw new IOException("Http Response Code : " + rc);
}
InputStream httpInput = fcon.openDataInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage img = EncodedImage.createEncodedImage(b, 0, b.length);
bitmp = resizeImage(img.getBitmap(), 100, 100);
}
catch(Exception e)
{
Dialog.alert("Exception : " + e.getMessage());
}
return bitmp;
}
public static Bitmap resizeImage(Bitmap originalImg, int newWidth, int newHeight)
{
Bitmap scaledImage = new Bitmap(newWidth, newHeight);
originalImg.scaleInto(scaledImage, Bitmap.FILTER_BILINEAR, Bitmap.SCALE_TO_FIT);
return scaledImage;
}
The Method resizeImage is called inside the method imageFromServer(String url).
1) the image from server is processed using EncodedImage img.
2) Bitmap bitmp = resizeImage(img.getBitmap(), 100, 100);
parameters are passed to resizeImage() and the return value from resizeImage() is set to Bitmap bitmp.

Resources