lunedì 1 settembre 2014

Ridimensionare le immagini

Oggi vedremo come creare un programma che legge un'immagine, la ridimensiona e la salva ridimensionata.
Creiamo un nuovo stack e mettiamoci un bottone per chiedere dove si trova il file dell'immagine che vogliamo. Livecode può importare come immagini  i seguenti formati: GIF, JPEG, PNG, BMP, XWD, XBM, XPM, PBM, PGM, PPM, PICT, EPS.
Per non appesantire troppo il codice mi limito ai formati più comuni, quindi il codice del pulsante sarà:

on mouseUp
   if there is an image 1 then
      delete the last image
   end if
   answer file "Seleziona l'immagine"
   put it into temp
   set itemdel to "."      
   if the last item of tolower(temp) is not among the items of "jpg.gif.png.jpeg.bmp" then
      answer "Il file selezionato non è un'immagine"
      exit MouseUp
   end if   
   import paint from file temp
   set the top of the last image to 75
   set the resizeQuality of last image to "best"
   set the inw of the last image to the width of the last image
   set the inh of the last image to the height of the last image
   set the intl of the last image to the topleft of the last image
end mouseUp

Andiamo a spiegarlo:
  • cancelliamo un eventuale immagine già presente
  • chiediamo la posizione del file
  • controlliamo che l'estensione del file sia una di quelle che ci piacciono
  • importiamo l'immagine, questa operazione crea una nuova immagine
  • la spostiamo in modo che non copra il pulsante
  • impostiamo la qualità per la modifica delle immagini su best (migliore)
  • salviamo le larghezza, altezza e posizione iniziali
Poi mettiamo uno scrollbar che chiameremo scala, e un pulsante per salvare. Se tutto  è andato bene, avremo qualcosa di simile a questo:

Il codice dello scrollbar sarà:

on scrollbarDrag newPosition
   put the inw of the last image into iniW
   put the inH of the last image into iniH
   put the inTl of the last image into iniTl
   set the width of the last image to round(iniW * newPosition / 100)
   set the height of the last image to round(iniH * newPosition / 100)
   set the topleft of the last image to iniTl
end scrollbarDrag

Come vedete riprendiamo i dati salvati e li usiamo come riferimento per scalare l'immagine quando moviamo l'indice dello scrollbar.

Ora manca il codice del pulsante Salva:

on mouseUp
   ask file "Fornire il nome del nuovo file:"
   export last image to file it as JPEG
end mouseUp



Il messaggio export supporta i seguenti formati di immagine: PBM, JPEG, GIF, BMP, PNG .

 Potete divertirvi a creare un programma che scala tutte le immagini in una cartella in automatico o creare qualche gioco che sfrutta gli effetti di ingrandimento o riduzione della dimensione delle immagini.

Nessun commento:

Posta un commento