cocoa - Converting between multiple image formats in Objective-C -


i want able to, being given path image, convert image image, different format. format mean .png, .bmp .jpg .tiff, etc. in pseudocode, easy:

image = [imageapi open: imagepath] [image save: imagepath withformat: imageformat] // important 

i have no idea how this, though. barely know more nsimage class when comes handling images), , not seem have answer problem (no simple save methods this). here list of formats i'd support:

  • .png
  • .tiff
  • .gif
  • .jpeg
  • .bmp
  • probably .pdf (if isn't complicated)

by support mean opening of , saving opened image of formats. there combinations here (15 ??? - think), write method each combination so:

[self savetiffimageintogifwithpath: path] (*15 !!!) 

but defenitely better use apis.

if chance along way have options like:

  • keep alpha or not
  • resize images

...i'd happy support them well, although they're optional. hope there's simple way this. thanks

ps: know there have been questions topic, iphone oriented (i want on mac) , none of them provided way multiple formats.

allright, peter's figure out. first, if you're working image paths, open directly file nsdata so:

nsdata* imgdata = [nsdata datawithcontentsoffile: filepath]; 

if you're working nsimage objects , difficult have path (for example nsimageview) (image nsimage object have):

nsdata* imgdata = [image tiffrepresentation]; 

now have image nsdata objects, nsbitmapimagerep:

nsbitmapimagerep* bitmap = [nsbitmapimagerep imagerepwithdata: imgdata]; 

and new nsdata object, different format:

nsdata* newdata = [bitmap representationusingtype: nspngfiletype properties: nil]; // used nspngfiletype example, // types wanted convert between (except pdf) supported 

finally, save newdata file:

[newdata writetofile: newpath atomically: yes] 

simple pie, once how works!


the support transparency , size control not difficult either:

  • the nsimage class provides support setting image's size (-setsize:)
  • the nsimagerep (superclass of nsbitmapimagerep) has -setalpha: method

just call when need. +1 cocoa!


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -