def convert_image(target_dir, output_dir, image_name): ''' Обрабатывает картинку. @param target_dir: string @param output_dir: string @param image_name: string ''' output_path = os.path.join(output_dir, image_name) if os.path.exists(output_path): print '%s already exists, skipping'%image_name return image = pdb.file_jpeg_load(os.path.join(target_dir, image_name), image_name) layer = image.layers[0] # Выравниваем уровни: # pdb.gimp_levels_stretch(layer) # Добавляем нерезкую маску: # pdb.plug_in_unsharp_mask(image, layer, 5, 0.5, 0) # Изменяем размер картинки: width, height = get_image_new_dimensions(image) pdb.gimp_image_scale(image, width, height) # Автоматически увеличиваем контраст: pdb.plug_in_c_astretch(image, layer) # Повышаем резкость: pdb.plug_in_sharpen(image, layer, 50) pdb.gimp_file_save(image, layer, output_path, image_name) pdb.gimp_image_delete(image)
def create_selection_image(self): vreturn = self.existImage() if not vreturn['isOk']: self.conn.send( json.dumps( vreturn ) ) return image = vreturn['image'] vreturn = self.isTifImage() if not vreturn['isOk']: self.conn.send( json.dumps( vreturn ) ) return is_empty = pdb.gimp_selection_is_empty( image ) if is_empty == 1: self.conn.send( json.dumps( { 'isOk': False, 'message': "No selection in '%s'" % self.pathfileImage } ) ) return non_empty, x1, y1, x2, y2 = pdb.gimp_selection_bounds( image ) selimage = image.selection.image.duplicate() selimage.crop( x2 - x1, y2 - y1, x1, y1 ) pdb.gimp_selection_sharpen( selimage ) channel = pdb.gimp_selection_save( selimage ) pdb.file_tiff_save( selimage, channel, self.pathfileImageSelect, "", 0) pdb.gimp_image_delete( selimage ) # data = { 'isOk': True, 'ulPixelSelect': { 'X': x1, 'Y': y1 } } data.update( self.paramImage ) self.conn.send( json.dumps( data ) )
def flip(file): fileabs = os.path.abspath(file) print(fileabs) file_dir, filename = os.path.split(fileabs) filename = filename.lower().replace('.png', '_mini.jpg') file_new = os.path.join(file_dir, filename) image = pdb.gimp_file_load(file, file) drawable = pdb.gimp_image_get_active_layer(image) #pdb.gimp_image_flip(image, ORIENTATION_HORIZONTAL) #pdb.gimp_file_save(image, drawable, file_new, file_new) pdb.file_jpeg_save(image, drawable, file_new, file_new, 0.8, 0, 1, 1, '', 0, 1, 0, 0) pdb.gimp_image_delete(image)
def change_num(image, inNumero): layer = pdb.gimp_image_get_active_layer(image) pdb.gimp_context_set_sample_transparent(True) pdb.gimp_image_select_contiguous_color(image, CHANNEL_OP_REPLACE,layer, 1, 1) pdb.gimp_selection_invert(image) _, x, y, x2, y2 = pdb.gimp_selection_bounds(image) xthird=x + ((x2 - x) // 4 * 3) y = _find_black_not_transparent(image, layer, xthird, y) pdb.gimp_context_set_sample_transparent(False) pdb.gimp_image_select_contiguous_color(image, CHANNEL_OP_REPLACE, layer, xthird, y) pdb.gimp_edit_clear(layer) if inNumero > 1: _, x, y, x2, y2 = pdb.gimp_selection_bounds(image) ymiddle = y + ( (y2 - y) // 2) keep = True while keep: if not _is_transparent(image, layer, x, ymiddle): keep = False pdb.gimp_context_set_sample_transparent(False) pdb.gimp_context_set_sample_threshold(1) pdb.gimp_image_select_contiguous_color(image, CHANNEL_OP_REPLACE, layer, x+1, ymiddle) pdb.gimp_context_set_sample_threshold(0.1) x += 1 pdb.gimp_edit_clear(layer) _, x1, y1, x2, y2 = pdb.gimp_selection_bounds(image) pdb.gimp_image_select_rectangle(image, CHANNEL_OP_REPLACE, x1, y1, x2-x1, y2-y1) filename = GRAPH_PATH + str(inNumero) + ".png" imagechiffre = pdb.gimp_file_load(filename, filename) layerchiffre = pdb.gimp_image_get_active_layer(imagechiffre) pdb.gimp_selection_all(imagechiffre) pdb.gimp_edit_copy(layerchiffre) pdb.gimp_image_delete(imagechiffre) floating_sel = pdb.gimp_edit_paste(layer,False) pdb.gimp_floating_sel_anchor(floating_sel)
def create_base_alphabet(font, font_size, directory_base): suffix = '.xbm' for c in string.printable: # Only need the first guard to prevent \x0b and \x0c, but meh if not ' ' <= c <= '\x7f': continue prefix = 'ascii0x%02x' % ord(c) filename = '%s%s' % (prefix, suffix) image = gimp.Image(1, 1, INDEXED) image.disable_undo() # necessary ? pdb.gimp_context_push() gimp.set_foreground( (0.0, 0.0, 0.0) ) x = y = border = 0 layer = pdb.gimp_text_fontname(image, None, x, y, c, border, True, font_size, PIXELS, font) if layer is None: print 'Failed to handle %r' % c else: image.resize(layer.width, layer.height, 0, 0) filepath = join(directory_base, filename) pdb.gimp_file_save(image, layer, filepath, '?') #pdb.file_xbm_save(RUN_NONINTERACTIVE, image, None, filename, filepath, '', 0, 0, 0) # find out how to properly call file_xbm_save so we can avoid this section with open(filepath, 'r+b') as file_h: lines = file_h.readlines() file_h.seek(0) for line in lines: if '_' in line: if '_hot' not in line: file_h.write(line.replace('_', prefix+'_')) else: file_h.write(line) file_h.truncate() pdb.gimp_image_delete(image) # necessary ? pdb.gimp_context_pop()
def plugin_main(file): """ Main plugin method """ image = pdb.gimp_file_load(file, file) drawable = pdb.gimp_image_get_active_layer(image) fileabs = os.path.abspath(file) #gprint('=== Input ==== ' + fileabs) file_dir, filename = os.path.split(fileabs) filename = filename[:-4] + '.jpg' file_new = os.path.join(OUTPUT_PATH, filename) pdb.file_jpeg_save(image, drawable, file_new, file_new, QUALITY, 0, 1, 1, '', 0, 1, 0, 0) pdb.gimp_image_delete(image) gprint('=== Output === ' + file_new)
def gif(image=None, suffix=None, fps=24): if not image: image = gimp.image_list()[0] file_path = pdb.gimp_image_get_filename(image)[:-4] if suffix: file_path += "_" + suffix.strip() file_path += ".gif" ms = int(1000.0 / fps) temp_image = False try: gimp.progress_init( "Save animated GIF @ {} fps = {} ms/frame as {}".format( fps, ms, file_path)) if pdb.gimp_image_base_type(image) != 2: temp_image = True image = pdb.gimp_image_duplicate(image) pdb.gimp_image_convert_indexed( image, 0, # dither-type=CONVERT-DITHER-NONE 0, # palette-type=CONVERT-PALETTE-GENERATE 255, # num-cols False, # alpha-dither False, # remove-unused "" # palette ) gimp.progress_update(50) pdb.file_gif_save( image, image.layers[0], file_path, file_path, True, # interlace True, # loop ms, # default-delay 2 # default-dispose ) gimp.progress_update(100) gimp.message("Saved animated GIF @ {} fps = {} ms/frame as {}".format( fps, ms, file_path)) finally: if temp_image: pdb.gimp_image_delete(image)
def create_base_alphabet(font, font_size, directory_base): suffix = '.xbm' for c_gen, c_prefix in ( (map(chr, xrange(ord('A'), ord('Z')+1)), 'upper'), (map(chr, xrange(ord('a'), ord('z')+1)), 'lower'), (map(chr, xrange(ord('0'), ord('9')+1)), 'number'), ): for c in c_gen: prefix = '%s%c' % (c_prefix, c) filename = '%s%s' % (prefix, suffix) image = gimp.Image(1, 1, INDEXED) image.disable_undo() # necessary ? pdb.gimp_context_push() gimp.set_foreground( (0.0, 0.0, 0.0) ) x = y = border = 0 layer = pdb.gimp_text_fontname(image, None, x, y, c, border, True, font_size, PIXELS, font) image.resize(layer.width, layer.height, 0, 0) filepath = join(directory_base, filename) pdb.gimp_file_save(image, layer, filepath, '?') #pdb.file_xbm_save(RUN_NONINTERACTIVE, image, None, filename, filepath, '', 0, 0, 0) # find out how to properly call file_xbm_save so we can avoid this crap with open(filepath, 'r+b') as file_h: lines = file_h.readlines() file_h.seek(0) for line in lines: if '_' in line: if '_hot' not in line: file_h.write(line.replace('_', prefix+'_')) else: file_h.write(line) file_h.truncate() pdb.gimp_image_delete(image) # necessary ? pdb.gimp_context_pop()
def pythonSaveToEdit(image): # Prep pdb.gimp_image_undo_group_start(image) pdb.gimp_context_push() # Code drawable = pdb.gimp_image_get_active_drawable(image) filename = pdb.gimp_image_get_filename(image) temp = filename.replace("_CLEAN", "") temp2 = temp.replace("_EDIT", "") filename = temp2.replace("_XCF", "") path = os.path.dirname(filename) path2 = os.path.dirname(filename) path += "_EDIT" path2 += "_XCF" name = os.path.basename(filename) out_file = os.path.join(path, name) out_xcf = os.path.join(path2, name) out_file = os.path.splitext(out_file)[0] + '.jpg' out_xcf = os.path.splitext(out_xcf)[0] + '.xcf' # Create folders if not os.path.exists(path): os.makedirs(path) if not os.path.exists(path2): os.makedirs(path2) # Merge visible layers in an image and export in jppeg new_image = pdb.gimp_image_duplicate(image) layer = pdb.gimp_image_merge_visible_layers(new_image, CLIP_TO_IMAGE) pdb.gimp_file_save(new_image, layer, out_file, out_file) pdb.gimp_image_delete(new_image) # Save in XCF pdb.gimp_file_save(image, drawable, out_xcf, out_xcf) pdb.gimp_image_clean_all(image) # Finish pdb.gimp_context_pop() pdb.gimp_image_undo_group_end(image) pdb.gimp_displays_flush()
def texte(inR,inG,inB,inFichier,highlight_text,change_numero): print("\tLoading image {}".format(inFichier)) image = pdb.gimp_file_load(inFichier,inFichier) color = (inR,inG,inB) # pdb.gimp_display_new(image) if highlight_text: print("\t\tHighlighting text...") effet_texte(color, image) if change_numero > 0: print("\t\tChanging number...") change_num(image, change_numero) pdb.gimp_selection_none(image) layer_id = pdb.gimp_image_get_layers(image)[1][0] layer = gimp.Item.from_id(layer_id) pdb.script_fu_add_bevel(image, layer, 5, False, False) drawable = pdb.gimp_image_get_active_drawable(image) pdb.file_png_save(image, drawable, inFichier, inFichier, 0,5,0,0,0,0,0) pdb.gimp_image_delete(image)
def \ superimpose_image_over_another_noninteractive( # image, # drawable, list_filenames, list_filenames_superimpose # horizontalLocation, # verticalLocation ) : nameFunction = "superimpose_image_over_another_interactive" print("----------------------------------------") print("%s : Enter" % (nameFunction)) IFS = ";" # listFiles = fileContents.split(IFS) listFiles = list_filenames.split(IFS) listFiles_superimpose = list_filenames_superimpose.split(IFS) print("%s : Number of elements in list = %d" % (nameFunction, len(listFiles))) print("%s : File list = %s" % (nameFunction, listFiles)) print("%s : Number of elements in list = %d" % (nameFunction, len(listFiles_superimpose))) print("%s : File list = %s" % (nameFunction, listFiles_superimpose)) if (len(listFiles) == 0): print("%s : Number of background image files = 0 : a") % (nameFunction) # errdialog = gtk.MessageDialog( # None, # 0, # gtk.MESSAGE_ERROR, # gtk.BUTTONS_OK, # "A) You must specify at least one background image file." # ) # errdialog.show_all() # errdialog.run() # raise Exception("You must specify at least one background image file.") elif (len(listFiles_superimpose) == 0): gimp.message( "B) You must specify at least one superimpose image file.") print("%s : Number of superimpose image files = 0 : a") % ( nameFunction) # raise Exception("You must specify at least one superimpose image file.") # elif (len(listFiles) == 1) : and elif (listFiles[0] == ''): gimp.message("C) You must specify at least one background image file.") print("%s : Number of background image files = 0 : b") % (nameFunction) # raise Exception("You must specify at least one background image file.") # elif (len(listFiles_superimpose) == 1) and elif (listFiles_superimpose[0] == ''): gimp.message( "D) You must specify at least one superimpose image file.") print("%s : Number of superimpose image files = 0 : b") % ( nameFunction) # raise Exception("You must specify at least one superimpose image file.") elif len(listFiles) != len(listFiles_superimpose): gimp.message( "E) The number of files specified must be the same for both background and superimpose images." ) print( "%s : The number of files specified must be the same for both background and superimpose images!" ) % (nameFunction) # raise Exception("The number of files specified must be the same for both background and superimpose images!") indexList = 0 for filename in listFiles: indexList = indexList + 1 print("%s : ========================================" % (nameFunction)) print("%s : Filename = %s" % (nameFunction, filename)) print("%s : ========================================" % (nameFunction)) if (not path.isfile(filename)): print("%s : > is NOT a file" % (nameFunction)) continue filename_superimpose = listFiles_superimpose[indexList - 1] print("%s : ========================================" % (nameFunction)) print("%s : Filename of image to superimpose = %s" % (nameFunction, filename_superimpose)) print("%s : ========================================" % (nameFunction)) if (not path.isfile(filename_superimpose)): print("%s : > is NOT a file" % (nameFunction)) gimp.progress_init("Superimposing one image over the other") image = pdb.gimp_file_load(filename, filename) drawable = pdb.gimp_image_get_active_layer(image) # Start a GIMP Undo group, as this will allow the actions of this Plugin to be undone in one step. pdb.gimp_undo_push_group_start(image) widthImage = image.width heightImage = image.height widthDrawable = drawable.width heightDrawable = drawable.height print("Width image = %s" % widthImage) print("Height image = %s" % heightImage) print("Width drawable = %s" % widthDrawable) print("Height drawable = %s" % heightDrawable) # print("Horizontal location = %s" % horizontalLocation) # print("Vertical location = %s" % verticalLocation) print("Image filename = %s" % image.filename) # Open the image file to be superimposed and get its drawable object. image_super = pdb.gimp_file_load(filename_superimpose, filename_superimpose) drawable_super = pdb.gimp_image_get_active_layer(image_super) print("Width super image = %s" % image_super.width) print("Height super image = %s" % image_super.height) print("Width super drawable = %s" % drawable_super.width) print("Height super drawable = %s" % drawable_super.height) # How many layers does the current image now contain? # # Use gimp-edit-copy and gimp-edit-paste? copy_result = pdb.gimp_edit_copy(drawable_super) if (copy_result == True): print("True") else: print("False") print("Selection copy result = %s" % copy_result) # pdb.gimp_drawable_update(drawable, horizontalLocation, verticalLocation, 384, 216) # The following operation should paste the image which is in the buffer, into a new layer of the # original image. pdb.gimp_edit_paste(drawable, True) widthImage = image.width heightImage = image.height widthDrawable = drawable.width heightDrawable = drawable.height print("Width image = %s" % widthImage) print("Height image = %s" % heightImage) print("Width drawable = %s" % widthDrawable) print("Height drawable = %s" % heightDrawable) # print("Horizontal location = %s" % horizontalLocation) # print("Vertical location = %s" % verticalLocation) # Move the # pdb.gimp_drawable_update() drawable_new = pdb.gimp_image_flatten(image) pdb.gimp_file_save(image, drawable_new, filename, filename) # End the GIMP Undo group. pdb.gimp_undo_push_group_end(image) # Close the image now that we have finished with it, otherwise it will use up memory unnecessarily. pdb.gimp_image_delete(image) # End of for loop. print("%s : Exit" % (nameFunction))
def \ scale_and_set_size_file_noninteractive( horizontalResolution, verticalResolution, interpolationMode, # 0,1,2,3 : 3 = INTERPOLATION_LANCZOS listFiles ) : nameFunction = "scale_and_set_size_noninteractive" print("%s : Enter" % (nameFunction)) print("%s : Checking if Interpolation mode value is valid" % (nameFunction)) if (interpolationMode == INTERPOLATION_LANCZOS): interpolationMode = 3 # if ((int(interpolationMode) < 0) or (int(interpolationMode) > 3)) : else: print("%s : Interpolation mode value is NOT valid = %s" % (nameFunction, str(interpolationMode))) raise Exception("Invalid value for parameter : interpolationMode") print("%s : Interpolation mode value IS valid = %s" % (nameFunction, interpolationMode)) debug = False fileHandle = open(listFiles, "r") filesList = fileHandle.read() fileHandle.close() listFiles = filesList.split("\n") print("%s : Number of elements in list = %d" % (nameFunction, len(listFiles))) print("%s : File list = %s" % (nameFunction, listFiles)) for filename in listFiles: try: print("%s : ========================================" % (nameFunction)) print("%s : Filename = %s" % (nameFunction, filename)) print("%s : ========================================" % (nameFunction)) if (not path.isfile(filename)): print("%s : > is NOT a file" % (nameFunction)) continue # Open the image file and get its drawable object. image = pdb.gimp_file_load(filename, filename) drawable = pdb.gimp_image_get_active_layer(image) # scale_and_set_size_interactive(image, drawable, horizontalResolution, verticalResolution, interpolationMode, filename) # Close the image now that we have finished with it, otherwise it will use up memory unnecessarily. pdb.gimp_image_delete(image) print("%s : Exit" % (nameFunction)) except: print("########################################") print("########################################") print("Something went wrong while attempting to") print("process the previous file; ") print("") print(" %s" % (filename)) print("") print("########################################") print("########################################")
def create_selection_image(self, socket): def existImage(): if self.pathfileImage in self.addedImages: image = self.addedImages[self.pathfileImage]['image'] if pdb.gimp_image_is_valid(image): return {'isOk': True, 'image': image} images = gimp.image_list() if len(images) == 0: return {'isOk': False, 'message': "Not exist images"} images_by_filename = [ item for item in images if item.filename == self.pathfileImage ] del images if len(images_by_filename) == 0: return { 'isOk': False, 'message': "Not exist image '{}'".format(self.pathfileImage) } image = images_by_filename[0] del images_by_filename if not pdb.gimp_image_is_valid(image): return { 'isOk': False, 'message': "Image '{}' is not valid".format(self.pathfileImage) } return {'isOk': True, 'image': image} r = existImage() if not r['isOk']: socket.send(json.dumps(r)) return image = r['image'] r = self._isTifImage() if not r['isOk']: socket.send(json.dumps(r)) return is_empty = pdb.gimp_selection_is_empty(image) if is_empty == 1: data = { 'isOk': False, 'message': "No selection in '{}'".format(self.pathfileImage) } socket.send(json.dumps(data)) return _non_empty, x1, y1, x2, y2 = pdb.gimp_selection_bounds(image) # Verify Version sel_image = image.duplicate( ) if self.isVersion2_10 else image.selection.image.duplicate() # sel_image.crop(x2 - x1, y2 - y1, x1, y1) pdb.gimp_selection_sharpen(sel_image) channel = pdb.gimp_selection_save(sel_image) # Verify Version if self.isVersion2_10: sel_layer = pdb.gimp_selection_float( channel, 0, 0) # Add selection how top layer pdb.gimp_image_remove_layer( sel_image, sel_image.layers[-1]) # Remove original layer pdb.file_tiff_save(sel_image, sel_layer, self.pathfileImageSelect, '', 0) else: pdb.file_tiff_save(sel_image, channel, self.pathfileImageSelect, "", 0) # pdb.gimp_image_delete(sel_image) data = {'isOk': True, 'ulPixelSelect': {'X': x1, 'Y': y1}} data.update(self.paramImage) socket.send(json.dumps(data))
def despeckle(fin, fout): image = pdb.gimp_file_load(fin, fin) drawable = pdb.gimp_image_get_active_layer(image) pdb.plug_in_despeckle(image, drawable, 3, 1, 7, 248) pdb.gimp_file_save(image, drawable, fout, fout) pdb.gimp_image_delete(image)
def simple_plugin(filename_background, filename_foreground, filename_result): nameProcedure = "simple_plugin" sleep_timer = 0 counter = 1 print("%s : Enter" % (nameProcedure)) # ---------------------------------------------------------------------------------------------- # Get the following from both the background and foreground image files; # # - image # - drawable # ---------------------------------------------------------------------------------------------- image_background = pdb.gimp_file_load(filename_background, filename_background) drawable_background = pdb.gimp_image_get_active_layer(image_background) image_foreground = pdb.gimp_file_load(filename_foreground, filename_foreground) drawable_foreground = pdb.gimp_image_get_active_layer(image_foreground) display_diagnostics(counter, image_background, image_foreground, drawable_background, drawable_foreground) counter = counter + 1 gimp.progress_init("Have got image and drawable from both files") time.sleep(sleep_timer) # ---------------------------------------------------------------------------------------------- # Start a GIMP Undo group, as this will allow the actions of this Plugin to be undone in one # step. # ---------------------------------------------------------------------------------------------- pdb.gimp_image_undo_group_start(image_background) # ---------------------------------------------------------------------------------------------- # Copy the foreground image. # ---------------------------------------------------------------------------------------------- copy_result = pdb.gimp_edit_copy(drawable_foreground) print("%s : Copy result = %s" % (nameProcedure, str(copy_result))) gimp.progress_init("Have copied foreground image into Buffer") time.sleep(sleep_timer) # ---------------------------------------------------------------------------------------------- # Paste the foreground image onto the background image. # ---------------------------------------------------------------------------------------------- use_gimp_edit_paste_as_new = False if use_gimp_edit_paste_as_new: pdb.gimp_edit_paste(drawable_background, True) else: image_background_new = pdb.gimp_edit_paste_as_new( drawable_background, True) if (image_background_new == -1): print( "%s : Attempted to paste from the Edit buffer, but it appears to be empty." % (nameProcedure)) exception_message = "\n\nAn Exception has been raised by the method;\n\n " + \ nameProcedure + \ "\n\nThis method attempted to paste from the Edit buffer, but it appears to be empty.\n\nAs a result, this Plugin is about to terminate!" raise Exception(exception_message) gimp.progress_init( "Have pasted foreground image from Buffer onto background image") time.sleep(sleep_timer) display_diagnostics(counter, image_background, image_foreground, drawable_background, drawable_foreground) counter = counter + 1 # ---------------------------------------------------------------------------------------------- # Flatten the modified background image down into one layer. # ---------------------------------------------------------------------------------------------- drawable_background = pdb.gimp_image_flatten(image_background) gimp.progress_init("Have flattened the background image") time.sleep(sleep_timer) display_diagnostics(counter, image_background, image_foreground, drawable_background, drawable_foreground) # ---------------------------------------------------------------------------------------------- # Save the background image into a specified file. # ---------------------------------------------------------------------------------------------- if use_gimp_edit_paste_as_new: pdb.gimp_file_save(image_background, drawable_background, filename_result, filename_result) else: pdb.gimp_file_save(image_background_new, drawable_background, filename_result, filename_result) gimp.progress_init("Have saved the background image") time.sleep(sleep_timer) # ---------------------------------------------------------------------------------------------- # End the GIMP Undo group which was started at the beginning of this Plugin. # ---------------------------------------------------------------------------------------------- pdb.gimp_image_undo_group_end(image_background) # ---------------------------------------------------------------------------------------------- # Close the GIMP images now that we have finished with them, otherwise they will use up memory # nnecessarily. # ---------------------------------------------------------------------------------------------- pdb.gimp_image_delete(image_foreground) pdb.gimp_image_delete(image_background) print("%s : Exit" % (nameProcedure))
def runMultipleFromList(self, filenames_foreground, seperator_character): """ Copy and paste the foreground image onto the background image, flatten the background image down into one layer, and then save the result to file. Parameters: NA Returns: NA Invoked by : runPlugin_multiple_fromList OverlayImageAgent.runMultipleFromFile Invokes : OverlayImageAgent.__getForegroundImageAndDrawable OverlayImageAgent.__displayDiagnosticData OverlayImageAgent.__run """ nameProcedure = "OverlayImageAgent::runMultipleFromList" print("%s : Enter" % (nameProcedure)) print("%s : filenames_foreground = %s" % (nameProcedure, filenames_foreground)) print("%s : seperator_character = %s" % (nameProcedure, seperator_character)) # Ascertain how many Foreground Images were passed to this Plugin. self.filenames_foreground = filenames_foreground.split( seperator_character) print("%s : Number of Foreground filenames = %d" % (nameProcedure, len(self.filenames_foreground))) gimp.progress_init( "Have got image and drawable from Background Image file") # Start a GIMP Undo group. # # This will allow the actions of this Plugin to be undone in one step. # pdb.gimp_image_undo_group_start(self.image_background) for filename_foreground in self.filenames_foreground: print("%s : filename_foreground = %s" % (nameProcedure, filename_foreground)) if path.isfile(filename_foreground): self.filename_foreground = filename_foreground print("%s : Filename Foreground image = %s" % (nameProcedure, self.filename_foreground)) print("%s : Length of filename = %d chars" % (nameProcedure, len(self.filename_foreground))) self.filename_result = self.__constructFilenameResult( self.filename_foreground) self.image_background = pdb.gimp_file_load( self.filename_background, self.filename_background) self.drawable_background = pdb.gimp_image_get_active_layer( self.image_background) print("%s : Filename background image = %s" % (nameProcedure, self.image_background.filename)) self.__getForegroundImageAndDrawable(self.filename_foreground) message = "<span foreground=\"black\" style=\"italic\">" + nameProcedure + " : Processing next Foreground Image</span>" self.__displayDiagnosticData(message) self.__run() # Close the GIMP Images now that we have finished with them, otherwise they will use up # memory unnecessarily. pdb.gimp_image_delete(self.image_foreground) pdb.gimp_image_delete(self.image_background) else: print("%s : Filename Foreground image DOESN'T exist = %s" % (nameProcedure, self.filename_foreground)) # ---------------------------------------------------------------------------------------------- # End the GIMP Undo group which was started at the beginning of this Plugin. # ---------------------------------------------------------------------------------------------- # pdb.gimp_image_undo_group_end(self.image_background) print("%s : Exit" % (nameProcedure))
def delete(self): pdb.gimp_image_delete(self.img)
def processList(self): nameMethod = self.nameClass + "::run" print("%s : Enter" % (nameMethod)) # Start a GIMP Undo group, as this will allow the actions of this Plugin to be undone in one step. # pdb.gimp_undo_push_group_start(image) indexList = 0 for filenameForeground in self.listFilenamesForeground: indexList = indexList + 1 # self.checkFiles(filename, filenameOverlay) self.imageBackground = pdb.gimp_file_load(self.filenameBackground, self.filenameBackground) self.drawableBackground = pdb.gimp_image_get_active_layer( self.imageBackground) self.imageForeground = pdb.gimp_file_load(filenameForeground, filenameForeground) self.drawableForeground = pdb.gimp_image_get_active_layer( self.imageForeground) print("%s : Processing ..." % (nameMethod)) print("%s : Background image = %s" % (nameMethod, self.filenameBackground)) print("%s : Overlay image = %s" % (nameMethod, filenameForeground)) # Display information about both of the current images. self.displayImageData() # How many layers does the current image now contain? # # Use gimp-edit-copy and gimp-edit-paste? self.overlayImage() # Move the # pdb.gimp_drawable_update() # self.drawableNew = pdb.gimp_image_flatten(self.imageNew) pdb.gimp_file_save(self.imageForeground, self.drawableForeground, filenameForeground, filenameForeground) # Close the images now that we have finished with it, otherwise they will use up memory unnecessarily. pdb.gimp_image_delete(self.imageForeground) pdb.gimp_image_delete(self.imageBackground) # End of for loop. # End the GIMP Undo group. # pdb.gimp_undo_push_group_end(image) print("%s : Enter" % (nameMethod))
def sheet(image=None, cols=0): if not image: image = gimp.image_list()[0] if not cols: best = (1, 10000000) for cols in range(1, len(image.layers) + 1): rows = (len(image.layers) + (cols - 1)) // cols (sheet_width, sheet_height) = (cols * image.width, rows * image.height) sheet_aspect_ratio = sheet_width / sheet_height if sheet_width > sheet_height else sheet_height / sheet_width if sheet_aspect_ratio < best[1]: best = (cols, sheet_aspect_ratio) cols = best[0] file_path = "{}_sheet_{}_frames_{}_columns_{}x{}.png".format( pdb.gimp_image_get_filename(image)[:-4], len(image.layers), cols, image.width, image.height) gimp.progress_init("Save sheet as {}".format(file_path)) rows = (len(image.layers) + (cols - 1)) // cols sheet = pdb.gimp_image_new(image.width * cols, image.height * rows, 0) try: sheet_layer = pdb.gimp_layer_new( sheet, sheet.width, sheet.height, 1, # type = RGBA-IMAGE "sprite sheet", 100, # opacity = 100 % 0 # mode = LAYER-MODE-NORMAL-LEGACY ) pdb.gimp_image_insert_layer(sheet, sheet_layer, None, 0) (row, col) = (0, 0) for (layer_index, layer) in enumerate(image.layers): pdb.gimp_selection_none(image) pdb.gimp_layer_resize_to_image_size(layer) pdb.gimp_edit_copy(layer) floating = pdb.gimp_edit_paste(sheet_layer, True) (left, top) = floating.offsets pdb.gimp_layer_translate(floating, col * image.width - left, row * image.height - top) pdb.gimp_floating_sel_anchor(floating) col += 1 if col >= cols: col = 0 row += 1 gimp.progress_update(100 * (layer_index + 1) / len(image.layers)) pdb.file_png_save( sheet, sheet_layer, file_path, None, True, # interlace 9, # compression True, # bkgd True, # gama True, # offs True, # phys True, # time ) gimp.message("All frames saved as {}".format(file_path)) finally: pdb.gimp_image_delete(sheet)
def flip(file): image = pdb.gimp_file_load(file, file) drawable = pdb.gimp_image_get_active_layer(image) pdb.gimp_image_flip(image, ORIENTATION_HORIZONTAL) pdb.gimp_file_save(image, drawable, file, file) pdb.gimp_image_delete(image)