kresala 0 Posted February 21, 2019 Share Posted February 21, 2019 Hola a tod@s! Tengo en GIMP dos archivos abiertos/preparados: 1) Es un archivo de 24x90 píxeles de 1bit con cuadrícula activada de 1x1 pixel (donde solo puede haber un cuadrado blanco o negro). 2) Una imagen (tarjeta de puntos) en jpg. Lo que quiero es colocar el archivo nº 2 dentro del archivo nº 1 y así poder adaptar dicha imagen y calcar los puntos deseados en negro (luego la capa de la imagen jpg la desactivo o la borro, quedando solo los píxeles deseados en color negro). Problema: Cuando hago esto, la imagen en jpg se distorsiona, también termina siendo una escala de grises, etc... y no lo consigo. Adjunto unas imágenes para que os hagáis una idea de lo que necesito. Alguna ayuda para hacer esto, ya que sino tendría que contar los puntos de cada línea e ir pintando uno a uno a mano, es decir, píxel a píxel... Gracias por adelantado. Saludos. Quote Link to post Share on other sites
APB 66 Posted February 22, 2019 Share Posted February 22, 2019 (edited) He creado un script, con la imprescindible ayuda del código encontrado en https://macscripter.net/viewtopic.php?id=45260, que crea lo que quieres. -- Creat amb ApplescriptObjC -- TEXT PER TRADUIR -- set peticioArxiu to "Arxiu inicial" set nomArxiuResultat to "Resultat Final.jpg" set peticioReticula to "Mida de la retícula:" set respostaPerDefecte to "Horitzontal, vertical" set botoCancel to "Cancel·lar" set botoQuadrada to "Quadrada" set botoRectangular to "Rectangular" set errorValorsRet to "Han de ser dos números separats per una coma." -- ** NO TRADUIR ** use scripting additions use framework "Foundation" use framework "AppKit" -- classes, constants, and enums used property NSString : a reference to current application's NSString property NSJPEGFileType : a reference to 3 property NSImage : a reference to current application's NSImage property NSBitmapImageRep : a reference to current application's NSBitmapImageRep property NSAlphaFirstBitmapFormat : a reference to 1 property NSCompositeSourceOver : a reference to 2 property NSTIFFFileType : a reference to 0 property NSPNGFileType : a reference to 4 property NSTIFFCompressionLZW : a reference to 5 property NSGraphicsContext : a reference to current application's NSGraphicsContext property NSCalibratedRGBColorSpace : a reference to current application's NSCalibratedRGBColorSpace -- Escullir arxiu imatge set arxiuImatge to POSIX path of (choose file of type "public.image" with prompt peticioArxiu) set carpetaResultat to POSIX path of (path to desktop folder) --(path to desktop folder as string) set arxiuResultat to NSString's stringWithString:(carpetaResultat & nomArxiuResultat) --Esborrar arxiu resultat anterior try tell application "Finder" to delete (POSIX file (carpetaResultat & nomArxiuResultat)) as alias end try --Demanar mida retícula de l'imatge set abc to "" repeat while abc is "" set aaa to display dialog peticioReticula default answer respostaPerDefecte buttons {botoCancel, botoQuadrada, botoRectangular} default button 3 if button returned of aaa is botoCancel then error number -128 set reticulaQuadrada to button returned of aaa is equal to botoQuadrada set aaa to text returned of aaa set AppleScript's text item delimiters to the "," try set columnesFinal to (first text item of aaa) as number set filesFinal to (second text item of aaa) as number set abc to "OK" on error display alert errorValorsRet as critical end try set AppleScript's text item delimiters to the "" end repeat -- load images and get the size set imatgeOriginal to NSBitmapImageRep's imageRepWithContentsOfFile:(NSString's stringWithString:arxiuImatge) set {width:columnesOrig, height:filesOrig} to imatgeOriginal's |size|() --calcular proporció set espaiPixelColumna to columnesOrig / columnesFinal if reticulaQuadrada then set espaiPixelFila to espaiPixelColumna else set espaiPixelFila to filesOrig / filesFinal end if -- make new bitmapImage set imageNova to (NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:columnesFinal pixelsHigh:filesFinal bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(NSCalibratedRGBColorSpace) bitmapFormat:NSAlphaFirstBitmapFormat bytesPerRow:0 bitsPerPixel:32) --- store the existing graphics context NSGraphicsContext's saveGraphicsState() -- set graphics context to new context based on the new bitmapImageRep (NSGraphicsContext's setCurrentContext:(NSGraphicsContext's graphicsContextWithBitmapImageRep:imageNova)) -- manipulant els pixels repeat with filaPixel from 0 to (filesFinal - 1) set filaPixelOrig to round (espaiPixelFila * filaPixel + espaiPixelFila / 2) repeat with columnaPixel from 0 to (columnesFinal - 1) set columnaPixelOrig to round (espaiPixelColumna * columnaPixel + espaiPixelColumna / 2) (imatgeOriginal's drawInRect:{origin:{x:columnaPixel, y:filaPixel}, |size|:{width:1, height:1}} fromRect:{origin:{x:columnaPixelOrig, y:filaPixelOrig}, |size|:{width:1, height:1}} operation:NSCompositeSourceOver fraction:1.0 respectFlipped:true hints:(missing value)) end repeat end repeat -- restore graphics state NSGraphicsContext's restoreGraphicsState() -- save bitmapImageRep as image set theData to (imageNova's representationUsingType:NSJPEGFileType |properties|:{NSImageCompressionFactor:1, NSImageProgressive:true}) theData's writeToFile:arxiuResultat atomically:true He usado esta imagen como ejemplo. Y el resultado: Este script se pega en el Editor de Scripts. Se puede ejecutar desde él o guardarlo como aplicación. Funcionamiento del script: - Pide que selecciones la imagen original - Pide el tamaño de la retícula, horizontal y vertical, la cantidad de puntos posibles. También puedes seleccionar si es cuadrada o rectangular. - Copia en una nueva imagen el pixel central de cada "cuadrado". Empieza por la esquina inferior izquierda. - Guarda esa imagen como Resultat Final.jpg en tu Escritorio. Edited February 23, 2019 by APB 2 Quote Link to post Share on other sites
Manolitto 31 Posted February 22, 2019 Share Posted February 22, 2019 😳 Guau. Quote Link to post Share on other sites
kresala 0 Posted February 22, 2019 Author Share Posted February 22, 2019 (edited) Mil gracias por tu trabajo de investigación!!! Pero me asaltan varias dudas... No sé que hacer con las líneas de programación, no sé que hacer con ello, ni donde colocarlo, etc... No me deja ver el resultado, la imagen es muy enana, pero parece ser lo que busco (cuadrados blancos y negros). También comentar que este proceso es algo que necesitamos los tejedores a máquina, de hecho, quiero hacer un videotutorial para que ayudar a la gente a hacerlo, por lo que me gustaría saber... si luego se puede hacer tanto en la versión GIMP de Windows como en la de Mac, incluso Linux. Por cierto la imagen que has usado de referencia es muy "perfecta"... me imagino que funcionará también con la del ejemplo. Lo adjunto. Gracias de nuevo!!!. Saludos. Edited February 22, 2019 by kresala Quote Link to post Share on other sites
APB 66 Posted February 22, 2019 Share Posted February 22, 2019 (edited) He añadido la explicación pendiente en el mensaje inicial. Como digo en esta explicación es un script de AppleScriptObjC y solo funcionará con Mac's. No tiene nada que ver con Gimp ni su Script-Fu. La imagen es enana puesto que pides un pixel por cuadrado, investigando un poco más encontraría la manera de ajustar la resolución pero importa poco para lo que necesitas. Arrastra la imagen de mi mensaje al escritorio y la abres. La imagen que has colgado falla por no ser proporcional. Tiene 30 columnas y 54 filas con 304 × 750 píxeles. El largo debería ser 304/30*54 = 547 píxeles. Si la ajustas y contrastas los colores seguro que te funcionará 🤥. He modificado el script para que se pueda elegir entre una retícula cuadrada o rectangular. He ajustado tu imagen, con Gimp 😉, a los 304x547 y contrastado la imagen, para que no haya grises, y aquí tienes el resultado. Tu imagen ajustada: El resultado: Aunque al principio también lo pensé, el resultado es el que tiene que ser. PD: Pregunta sin miedo. 🙂 PD2: Si el tema de ajustar las proporciones es una molestia no hay problema en modificar el script para que calcule filas y columnas de diferente tamaño. Será lo más sencillo que hecho con él 😄. Edited February 22, 2019 by APB 1 Quote Link to post Share on other sites
kresala 0 Posted February 23, 2019 Author Share Posted February 23, 2019 Hola de nuevo!!! Gracias... lo estoy probando pero como es fin de semana tengo poco tiempo... Lo que me ocurre es lo siguiente... debido a que luego haría un videotutorial sobre ello, por eso quería hacerlo funcionar en GIMP y así, de este modo, que llegara a ser fácil para todo el mundo. Esto me soluciona a mi, pero no es la solución definitiva de lo que busco. ¿podría ser que no lo puedo conseguir hacer directamente en GIMP o incluso en Photoshop??? Gracias! Saludos! Quote Link to post Share on other sites
APB 66 Posted February 23, 2019 Share Posted February 23, 2019 (edited) Hace 5 horas, kresala dijo: ¿podría ser que no lo puedo conseguir hacer directamente en GIMP o incluso en Photoshop??? Estoy seguro que puedes crear un script tanto para Gimp como para Photoshop que haga esto. Gimp usa Script-Fu y Photoshop admite varios, entre ellos JavaScript. Solo que yo no puedo hacerlos: - He visto un poco de Script-Fu mientras buscaba una solución a tu pregunta y me pareció lo suficientemente diferente a “mis conocimientos” para no intentarlo. - No me importaría aprender JavaScript pero como no tengo el Photoshop no podría hacer las mil y una pruebas necesarias para que funcione bien. Puedes solicitar ayuda en algún foro de Gimp, realmente es un script muy sencillo cuando se tiene claro que hacer. Si te apetece aprender Script-Fu, si pasas muchas horas con Gimp haciendo trabajos repetitivos te sería útil, puedo detallarte los pasos de mi script para que los “traduzcas” a ese lenguaje. Si te decides por Photoshop podría crearte el script en JavaScript dejándote a ti las instrucciones que interactúen con el programa (crear imagen, seleccionar un pixel, copiarlo, pegarlo, guardar documento, etc.) y las pruebas. PD: He modificado mínimamente el script. Son cambios "estéticos" tanto en la ejecución como en el propio script. Edited February 23, 2019 by APB 1 Quote Link to post Share on other sites
kresala 0 Posted February 23, 2019 Author Share Posted February 23, 2019 De acuerdo, mil gracias... Mis conocimientos de programación son nulos, con lo que no podría embarcarme en algo tan complicado... Pero mil gracias por tu inestimable ayuda!!! Esta semana veré si consigo que funcione lo del script y te cuento de nuevo... Gracias de nuevo! Saludos!. Quote Link to post Share on other sites
kresala 0 Posted February 25, 2019 Author Share Posted February 25, 2019 (edited) Hola de nuevo!!! Primero mil gracias por todo!!! No me sentía capaz de hacer esto de los Scripts, pero lo he conseguido... te cuento dudas: 1) Se me olvidó decirte que el fichero resultante lo necesito en PNG (blanco y negro), sino al programa que va no lo reconoce y da error. En la parte del código >>> set nomArxiuResultat to "Resultat Final.jpg >>> se lo he cambiado a la extensión .PNG y parece funcionar... pero me he dado cuenta de varios problemas... uno de ellos es que aumentando la imagen, no está en blanco y negro, sino que aparece algún gris muy oscuro... no sé si se apreciara en la foto adjunta con el zoom de GIMP. Esa imagen me la ha hecho perfecta a no ser por eso, cambios de colores en algunos píxeles/cuadrados. Qué opinas? Fácil solución para que solo utilice B&N? 2) En otra de las imágenes ha reconocido perfectamente los huecos, pero usa diferentes escalas de grises... he probado con varias tarjetas y ocurre lo mismo, incluso si le pongo que lo haga con JPG... adjunto foto... Si conseguimos que funcione bien... me gustaría también hacer el tutorial para los que tienen Windows (pero no a través de PhotoShop debido a que es de pago), y a través de Gimp dices que no eres capaz... alguna otra forma? Windows no tiene algo parecido al Editor del Mac? Cuál es el mejor foro de Gimp? Muchas gracias. Edited February 25, 2019 by kresala Quote Link to post Share on other sites
APB 66 Posted February 26, 2019 Share Posted February 26, 2019 (edited) Este nuevo script, casi idéntico al anterior, genera la imagen en grises. La anterior si usabas una imagen a todo color el resultado también era a color. - No sé, ¿aún?, como contrastar los grises. Deberás usar Gimp para que solo haya blancos y negros puros. - Guarda la imagen como .PNG - De Windows ni idea. Y lo mismo para Gimp, lo tengo pero casi nunca lo uso. - Como ya has descubierto, puedes cambiar/traducir los textos que aparecen modificándolos en las primeras líneas de código. -- Creat amb ApplescriptObjC -- TEXT PER TRADUIR -- set idioma_sistema to items 1 thru 2 of user locale of (get system info) as string if idioma_sistema is "ca" then --Català set peticioArxiu to "Arxiu inicial" set nomArxiuResultat to "Resultat Final.png" set peticioReticula to "Mida de la retícula:" set respostaPerDefecte to "Horitzontal, vertical" set botoCancel to "Cancel·lar" set botoQuadrada to "Quadrada" set botoRectangular to "Rectangular" set errorValorsRet to "Han de ser dos números separats per una coma." else if idioma_sistema is "es" then --Castellà set peticioArxiu to "Archivo inicial" set nomArxiuResultat to "Resultado Final.png" set peticioReticula to "Tamaño de la retícula:" set respostaPerDefecte to "Horizontal, vertical" set botoCancel to "Cancelar" set botoQuadrada to "Cuadrada" set botoRectangular to "Rectangular" set errorValorsRet to "Han de ser dos números separados por una coma." else --anglés set peticioArxiu to "Initial file" set nomArxiuResultat to "Final result.png" set peticioReticula to "Size of grid:" set respostaPerDefecte to "Horitzontal, vertical" set botoCancel to "Cancel" set botoQuadrada to "Square" set botoRectangular to "Rectangular" set errorValorsRet to "They must be two numbers separed by a comma." end if -- ** NO TRADUIR ** use scripting additions use framework "Foundation" use framework "AppKit" -- classes, constants, and enums used property NSString : a reference to current application's NSString property NSImage : a reference to current application's NSImage property NSBitmapImageRep : a reference to current application's NSBitmapImageRep property NSGraphicsContext : a reference to current application's NSGraphicsContext property NSCalibratedRGBColorSpace : a reference to current application's NSCalibratedRGBColorSpace property NSCalibratedWhiteColorSpace : a reference to current application's NSCalibratedWhiteColorSpace property NSTIFFCompressionLZW : a reference to current application's NSTIFFCompressionLZW --a reference to 5 property NSBitmapImageFileTypeJPEG : a reference to current application's NSBitmapImageFileTypeJPEG property NSBitmapImageFileTypeTIFF : a reference to current application's NSBitmapImageFileTypeTIFF property NSBitmapImageFileTypePNG : a reference to current application's NSBitmapImageFileTypePNG property NSBitmapImageFileTypeBMP : a reference to current application's NSBitmapImageFileTypeBMP property NSBitmapFormatAlphaFirst : a reference to current application's NSBitmapFormatAlphaFirst property NSBitmapFormatAlphaNonpremultiplied : a reference to current application's NSBitmapFormatAlphaNonpremultiplied property NSCompositingOperationSourceOver : a reference to current application's NSCompositingOperationSourceOver property NSCompositingOperationCopy : a reference to current application's NSCompositingOperationCopy property NSColorRenderingIntentSaturation : a reference to current application's NSColorRenderingIntentSaturation property NSColorRenderingIntentDefault : a reference to current application's NSColorRenderingIntentDefault property genericGrayColorSpace : a reference to current application's genericGrayColorSpace property NSColorSpace : a reference to current application's NSColorSpace -- Escullir arxiu imatge set arxiuImatge to POSIX path of (choose file of type "public.image" with prompt peticioArxiu) set carpetaResultat to POSIX path of (path to desktop folder) --(path to desktop folder as string) set arxiuResultat to NSString's stringWithString:(carpetaResultat & nomArxiuResultat) --Esborrar arxiu resultat anterior try tell application "Finder" to delete (POSIX file (carpetaResultat & nomArxiuResultat)) as alias end try --Demanar mida retícula de l'imatge set abc to "" repeat while abc is "" set aaa to display dialog peticioReticula default answer respostaPerDefecte buttons {botoCancel, botoQuadrada, botoRectangular} default button 3 if button returned of aaa is botoCancel then error number -128 set reticulaQuadrada to button returned of aaa is equal to botoQuadrada set aaa to text returned of aaa set AppleScript's text item delimiters to the "," try set columnesFinal to (first text item of aaa) as number set filesFinal to (second text item of aaa) as number set abc to "OK" on error display alert errorValorsRet as critical end try set AppleScript's text item delimiters to the "" end repeat -- load images and get the size set imatgeOriginal to NSBitmapImageRep's imageRepWithContentsOfFile:(NSString's stringWithString:arxiuImatge) set {width:columnesOrig, height:filesOrig} to imatgeOriginal's |size|() --set ddd to imatgeOriginal's scale() --calcular proporció set espaiPixelColumna to columnesOrig / columnesFinal if reticulaQuadrada then set espaiPixelFila to espaiPixelColumna else set espaiPixelFila to filesOrig / filesFinal end if -- make new bitmapImage -- Imatge a tot color set imatgeNova to (NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:columnesFinal pixelsHigh:filesFinal bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(NSCalibratedRGBColorSpace) bitmapFormat:NSBitmapFormatAlphaFirst bytesPerRow:0 bitsPerPixel:32) --- store the existing graphics context NSGraphicsContext's saveGraphicsState() -- set graphics context to new context based on the new bitmapImageRep (NSGraphicsContext's setCurrentContext:(NSGraphicsContext's graphicsContextWithBitmapImageRep:imatgeNova)) -- manipulant els pixels repeat with filaPixel from 0 to (filesFinal - 1) set filaPixelOrig to round (espaiPixelFila * filaPixel + espaiPixelFila / 2) repeat with columnaPixel from 0 to (columnesFinal - 1) set columnaPixelOrig to round (espaiPixelColumna * columnaPixel + espaiPixelColumna / 2) (imatgeOriginal's drawInRect:{origin:{x:columnaPixel, y:filaPixel}, |size|:{width:1, height:1}} fromRect:{origin:{x:columnaPixelOrig, y:filaPixelOrig}, |size|:{width:1, height:1}} operation:NSCompositingOperationCopy fraction:1.0 respectFlipped:true hints:(missing value)) end repeat end repeat -- converteix el resultat a grisos set imatgeNova to (imatgeNova's bitmapImageRepByConvertingToColorSpace:(NSColorSpace's genericGrayColorSpace) renderingIntent:NSColorRenderingIntentDefault) -- restore graphics state NSGraphicsContext's restoreGraphicsState() -- save bitmapImageRep as image set theData to (imatgeNova's representationUsingType:NSBitmapImageFileTypePNG |properties|:{NSImageInterlaced:true}) theData's writeToFile:arxiuResultat atomically:true Edited February 26, 2019 by APB 2 Quote Link to post Share on other sites
kresala 0 Posted February 26, 2019 Author Share Posted February 26, 2019 Mil gracias de nuevo... Funciona mejor con lo de los grises por si la original fuera en color... después de dejármelo en PNG, voy a GIMP y lo paso a 1bit... por lo que pasa todo lo que está en gris a negro... con lo que queda perfecto... y me ahorro un trabajo de la pera. El otro día grabe el Script como Aplicación en ARCHIVO/GUARDAR, escribo el nombre del Script, carpeta deseada y escojo "Aplicación" y me generó la aplicación automáticamente para así poder compartirla... ahora quiero hacer lo mismo ya que has hecho cambias en el código y no me deja crearla. Me dice lo siguiente: (adjunto foto) ¿qué estoy haciendo mal? Gracias. P.D.: Si alguien sabe hacer esto a través de Windows y/o GIMP para Windows que me eche una mano. Saludos. Quote Link to post Share on other sites
APB 66 Posted February 26, 2019 Share Posted February 26, 2019 (edited) A veces el editor se lía con el ObjC. Cuando te pase escribes un espacio en una linea vacía y ya lo podrás guardar. La opción de la retícula cuadrada la he mantenido por si alguna vez tenéis un archivo que no esté bien "terminado" de un lado, o sea que le sobre o le falte espacio para hacer que la retícula sea perfecta (como en mi imagen de prueba). Eso si, siempre deberéis girar la imagen para que el fallo esté arriba. Si siempre dejáis los archivos perfectos, como tus muestras, no la necesitareis nunca. Edited February 26, 2019 by APB 1 Quote Link to post Share on other sites
kresala 0 Posted February 26, 2019 Author Share Posted February 26, 2019 (edited) Ya lo he grabado!!! Sobre el botón "Cuadrado" te lo iba a preguntar pero veo que te has adelantado. Sin tu ayuda no hubiera podido con todo ello!!! Mil gracias por tu tiempo!!! Saludos!!! Edited February 26, 2019 by kresala Quote Link to post Share on other sites
APB 66 Posted February 26, 2019 Share Posted February 26, 2019 (edited) Viendo que lo has traducido a más idiomas he creado un "selector idiomático". Por defecto saldrá en inglés si el usuario no trabaja en alguno de los dos primeros. Le puedes añadir más si te apetece. PD: Nunca traduzco mis scripts hasta el final, con los cambios que les termino haciendo sería aumentarme el trabajo. Edited February 26, 2019 by APB Quote Link to post Share on other sites
Manolitto 31 Posted February 26, 2019 Share Posted February 26, 2019 Da gusto leeros. 🙂 Una cita de APB en algún crédito una vez lo tengas todo listo, está merecida ¿no? 🙂 Saludos, Manolo Quote Link to post Share on other sites
kresala 0 Posted February 26, 2019 Author Share Posted February 26, 2019 En cuanto a los idiomas no me importa que estén los dos a la vez!!! Pero gracias de todos los modos!!! Y lo siento, soy nuevo en esto... no había caído en ello... le haré una referencia en los comentarios de mi blog cuando prepare en un futuro cercano el post sobre ello, soy el blogger de knitstudium.com , un blog sobre tricotosas y también hablo sobre el hackeo de las electrónicas a través de Arduino-AYAB, https://ayab-knitting.com También le pondré dentro del Script!!! Desde luego que se lo merece!!! Saludos!!! 1 Quote Link to post Share on other sites
APB 66 Posted February 26, 2019 Share Posted February 26, 2019 Quedaría pendiente el “guion” de ayuda para que hagan la versión Windows. AppleScript tiene unas instrucciones muy descriptivas, no creo que nadie que sea capaz de crear la versión Windows no entienda cada uno de los pasos. Hasta las ObjectiveC usadas tienen unos nombre lo suficientemente claros para entender su función. Si realmente piensas que lo necesitaran tampoco sería un gran trabajo. Quote Link to post Share on other sites
kresala 0 Posted February 26, 2019 Author Share Posted February 26, 2019 Gracias APB, pero a mi eso se me escapa, no tengo ni idea y se me hace complicado... espero poder ir preguntando por ahí... por si alguien me ayuda en "traducirlo" para Windows... Espero tener suerte, ya que solo para Mac es complicado, ya que no todo el mundo tiene este sistema operativo... Tendré que investigar!!! Quote Link to post Share on other sites
kresala 0 Posted February 26, 2019 Author Share Posted February 26, 2019 Por cierto, @APB tengo una duda sobre el código, en una de las líneas del código del principio indica esto: set peticioReticula to "Mida de la retícula:" En que caso me va a pedir dicha medida? (por el momento no me ha ocurrido en ningún caso!!!) la traducción cuál es? Medida de la retícula? A qué se refiere? Gracias de nuevo!!! Quote Link to post Share on other sites
APB 66 Posted February 26, 2019 Share Posted February 26, 2019 Te la pide cada vez, cuando le indicas la cantidad de puntos horizontales y verticales. Lo llamé “retícula” pero si prefieres llamarlo de otra forma eres libre de modificarlo. La traducción la tienes en el último cambio que he hecho en el código “Tamaño de la retícula”. 1 Quote Link to post Share on other sites
kresala 0 Posted February 26, 2019 Author Share Posted February 26, 2019 Ah es verdad, que despiste!!! Mil gracias de nuevo!!! Saludos!!! 1 Quote Link to post Share on other sites
APB 66 Posted March 7, 2019 Share Posted March 7, 2019 (edited) Aunque probablemente ya habrás terminado de convertir los archivos, he conseguido que el programa contraste la imagen y que la nueva imagen sea de 1 bit por pixel, como querías. Así no tienes que abrir la imagen en Gimp para terminar el trabajo. -- Creat amb ApplescriptObjC -- TEXT PER TRADUIR -- set idioma_sistema to items 1 thru 2 of user locale of (get system info) as string if idioma_sistema is "ca" then --Català set peticioArxiu to "Arxiu inicial" set nomArxiuResultat to "Resultat Final.png" set peticioReticula to "Mida de la retícula:" set respostaPerDefecte to "Horitzontal, vertical" set botoCancel to "Cancel·lar" set botoQuadrada to "Quadrada" set botoRectangular to "Rectangular" set errorValorsRet to "Han de ser dos números separats per una coma." else if idioma_sistema is "es" then --Castellà set peticioArxiu to "Archivo inicial" set nomArxiuResultat to "Resultado Final.png" set peticioReticula to "Tamaño de la retícula:" set respostaPerDefecte to "Horizontal, vertical" set botoCancel to "Cancelar" set botoQuadrada to "Cuadrada" set botoRectangular to "Rectangular" set errorValorsRet to "Han de ser dos números separados por una coma." else --anglés set peticioArxiu to "Initial file" set nomArxiuResultat to "Final result.png" set peticioReticula to "Size of grid:" set respostaPerDefecte to "Horitzontal, vertical" set botoCancel to "Cancel" set botoQuadrada to "Square" set botoRectangular to "Rectangular" set errorValorsRet to "They must be two numbers separed by a comma." end if -- ** NO TRADUIR ** use scripting additions use framework "Foundation" use framework "AppKit" -- classes, constants, and enums used property NSString : a reference to current application's NSString property NSImage : a reference to current application's NSImage property NSColor : a reference to current application's NSColor property NSColorSpace : a reference to current application's NSColorSpace property NSBitmapImageRep : a reference to current application's NSBitmapImageRep property NSCalibratedRGBColorSpace : a reference to current application's NSCalibratedRGBColorSpace property NSCalibratedWhiteColorSpace : a reference to current application's NSCalibratedWhiteColorSpace property NSTIFFCompressionLZW : a reference to current application's NSTIFFCompressionLZW --a reference to 5 property NSBitmapImageFileTypeJPEG : a reference to current application's NSBitmapImageFileTypeJPEG property NSBitmapImageFileTypeTIFF : a reference to current application's NSBitmapImageFileTypeTIFF property NSBitmapImageFileTypePNG : a reference to current application's NSBitmapImageFileTypePNG property NSBitmapImageFileTypeBMP : a reference to current application's NSBitmapImageFileTypeBMP property NSBitmapFormatAlphaFirst : a reference to current application's NSBitmapFormatAlphaFirst property NSColorRenderingIntentDefault : a reference to current application's NSColorRenderingIntentDefault property genericGrayColorSpace : a reference to current application's genericGrayColorSpace -- Escullir arxiu imatge set arxiuImatge to POSIX path of (choose file of type "public.image" with prompt peticioArxiu) set carpetaResultat to POSIX path of (path to desktop folder) --(path to desktop folder as string) set arxiuResultat to NSString's stringWithString:(carpetaResultat & nomArxiuResultat) set arxiuResultat2 to NSString's stringWithString:(carpetaResultat & "previa " & nomArxiuResultat) --Esborrar arxiu resultat anterior try tell application "Finder" to delete (POSIX file (carpetaResultat & nomArxiuResultat)) as alias end try --Demanar mida retícula de l'imatge set abc to "" repeat while abc is "" set aaa to display dialog peticioReticula default answer respostaPerDefecte buttons {botoCancel, botoQuadrada, botoRectangular} default button 3 if button returned of aaa is botoCancel then error number -128 set reticulaQuadrada to button returned of aaa is equal to botoQuadrada set aaa to text returned of aaa set AppleScript's text item delimiters to the "," try set columnesFinal to (first text item of aaa) as number set filesFinal to (second text item of aaa) as number set abc to "OK" on error display alert errorValorsRet as critical end try set AppleScript's text item delimiters to the "" end repeat -- carregar imatge original set imatgeOriginal to NSBitmapImageRep's imageRepWithContentsOfFile:(NSString's stringWithString:arxiuImatge) -- Contrastar la imatge -- Si es vol una imatge en grissos molt contrastada millor primer passar-la a grisos abans de contrastar set imatgeOriginal to (imatgeOriginal's bitmapImageRepByConvertingToColorSpace:(NSColorSpace's genericGrayColorSpace) renderingIntent:NSColorRenderingIntentDefault) set imatgeOriginal to current application's CIImage's imageWithData:(imatgeOriginal's TIFFRepresentation()) -- aplicar filtre imatge - Ha de ser una CIImatge - aquestes imatges sempre son RGB set filtreContrast to current application's CIFilter's filterWithName:"CIColorControls" filtreContrast's setDefaults() filtreContrast's setValue:imatgeOriginal forKey:"inputImage" filtreContrast's setValue:1.0 forKey:"inputSaturation" -- valor inicial 1.0 filtreContrast's setValue:0.0 forKey:"inputBrightness" -- valor inicial 0.0 filtreContrast's setValue:100.0 forKey:"inputContrast" -- valor inicial 1.0 set imatgeOriginal to NSBitmapImageRep's alloc()'s initWithCIImage:(filtreContrast's outputImage()) -- converteix imatgeOriginal a grisos set imatgeOriginal to (imatgeOriginal's bitmapImageRepByConvertingToColorSpace:(NSColorSpace's genericGrayColorSpace) renderingIntent:NSColorRenderingIntentDefault) --mida set {width:columnesOrig, height:filesOrig} to imatgeOriginal's |size|() --calcular proporció set espaiPixelColumna to columnesOrig / columnesFinal if reticulaQuadrada then set espaiPixelFila to espaiPixelColumna else set espaiPixelFila to filesOrig / filesFinal end if -- crear la nova imatge d'un bit set imatgeNova to (NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:columnesFinal pixelsHigh:filesFinal bitsPerSample:1 samplesPerPixel:1 hasAlpha:false isPlanar:false colorSpaceName:(NSCalibratedWhiteColorSpace) bitmapFormat:0 bytesPerRow:0 bitsPerPixel:1) -- manipulant els pixels repeat with filaPixel from 0 to (filesFinal - 1) set filaPixelOrig to round (espaiPixelFila * filaPixel + espaiPixelFila / 2) repeat with columnaPixel from 0 to (columnesFinal - 1) set columnaPixelOrig to round (espaiPixelColumna * columnaPixel + espaiPixelColumna / 2) --pintar imatge 1 bit set valorGris to (imatgeOriginal's colorAtX:columnaPixelOrig y:filaPixelOrig)'s whiteComponent() (imatgeNova's setColor:(NSColor's colorWithCalibratedWhite:(round (valorGris)) alpha:1) atX:columnaPixel y:filaPixel) end repeat end repeat -- save bitmapImageRep as image set theData to (imatgeNova's representationUsingType:NSBitmapImageFileTypePNG |properties|:{NSImageInterlaced:true}) theData's writeToFile:arxiuResultat atomically:true Edited March 7, 2019 by APB 1 Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.