Ejemplo n.º 1
0
def createThumbnails(images):
    """Makes thumbnail images for all the image files, in the THUMBDIR."""
    for i in images:
        infile = os.path.join(IMAGEDIR, i)
        outfile = os.path.join(THUMBDIR, i)
        # Skip already-existing thumbnails
        if os.path.isfile(outfile): continue

        a = PythonMagick.Image(infile)
        size = a.size()
        w = size.width()
        h = size.height()
        aspectRatio = float(w) / float(h)
        if aspectRatio > 1.0:
            # Resize based on width
            scalefactor = float(w) / THUMBSIZE
            height = int(h / scalefactor)
            g = PythonMagick.Geometry(THUMBSIZE, height)
        else:
            # Resize based on height
            scalefactor = float(h) / THUMBSIZE
            width = int(w / scalefactor)
            g = PythonMagick.Geometry(width, THUMBSIZE)
        a.resize(g)
        a.write(outfile)
Ejemplo n.º 2
0
 def insert_picture(self):
     path, _ = QFileDialog.getOpenFileName(
         self, "Insert image", "",
         "PNG Images (*.png);;JPEG images (*.jpg);;All files (*.*)")
     try:
         file_ext = splitext(path)
         if file_ext in IMAGE_EXTENSIONS:
             cursor = self.editor.textCursor()
             loc = os.path.join(BUFFER, 'temp-image.' + DEFAULT_IMAGE_TYPE)
             image = PythonMagick.Image(
                 path.encode('ascii', errors='xmlcharrefreplace'))
             if image.size().width() > MAX_IMAGE_SIZE:
                 image.resize(
                     PythonMagick.Geometry(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE))
             image.write(loc)
             f = open(loc, 'rb')
             heximg = base64.b64encode(f.read())
             f.close()
             if cursor.positionInBlock() != 0: cursor.insertBlock()
             cursor.insertHtml('<img src="data:image/' +
                               DEFAULT_IMAGE_TYPE + ';base64,' + heximg +
                               '" />')
             cursor.insertBlock()
     except Exception as e:
         self.dialog_critical(str(e))
Ejemplo n.º 3
0
def cutPng():
    cf = ConfigParser.ConfigParser()
    cf.read("setting.conf")
    cutw = int(cf.get("position", "cut_width"))
    cuth = int(cf.get("position", "cut_height"))
    startx = int(cf.get("position", "cut_start_position_x"))
    starty = int(cf.get("position", "cut_start_position_y"))
    srcPath = cf.get("document", "cut_srcouce_document")
    desPath = cf.get("document", "cut_destination_document")

    if (os.path.exists(srcPath)):
        pngNameList = os.listdir(srcPath)
    else:
        print('document %s not exists' % os.path.abspath(srcPath))
        sys.exit(0)

    for pngName in pngNameList:
        if (pngName[-4:] == '.png'):
            srcFullPath = os.path.abspath(os.path.join(srcPath, pngName))
            desFullPath = os.path.abspath(os.path.join(desPath, pngName))
            if (os.path.exists(srcFullPath)):
                image = Magick.Image(srcFullPath)
                image.crop(Magick.Geometry(cutw, cuth, startx, starty))
                image.write(desFullPath)
            else:
                print('file %s not exists!!' % srcFullPath)
Ejemplo n.º 4
0
    def insertFromMimeData(self, source):

        cursor = self.textCursor()
        document = self.document()

        if source.hasUrls():

            for u in source.urls():
                file_ext = splitext(str(u.toLocalFile()))
                if u.isLocalFile() and file_ext in IMAGE_EXTENSIONS:
                    loc = os.path.join(BUFFER,
                                       'temp-image.' + DEFAULT_IMAGE_TYPE)
                    image = PythonMagick.Image(u.toLocalFile().encode(
                        'ascii', errors='xmlcharrefreplace'))
                    if image.size().width() > MAX_IMAGE_SIZE:
                        image.resize(
                            PythonMagick.Geometry(MAX_IMAGE_SIZE,
                                                  MAX_IMAGE_SIZE))
                    image.write(loc)
                    f = open(loc, 'rb')
                    heximg = base64.b64encode(f.read())
                    f.close()
                    if cursor.positionInBlock() != 0: cursor.insertBlock()
                    cursor.insertHtml('<img src="data:image/' +
                                      DEFAULT_IMAGE_TYPE + ';base64,' +
                                      heximg + '" />')
                    cursor.insertBlock()

                else:
                    # If we hit a non-image or non-local URL break the loop and fall out
                    # to the super call & let Qt handle it
                    break

            else:
                # If all were valid images, finish here.
                return

        elif source.hasImage():
            print "Passing on insertFromMimeData->source.hasImage()."
            #I have no idea if this code works, and I'm not sure what condition triggers this. --facade
            #loc = BUFFER + 'temp-image'
            #source.imageData().save(loc)
            #image = PythonMagick.Image( loc )
            #image.resize(PythonMagick.Geometry(150, 150))
            #image.write( loc )
            #qimage = QMimeData()
            #qimage.setImageData(QImage( loc ))
            #uuid = uuid.uuid4().hex
            #document.addResource(QTextDocument.ImageResource, uuid, qimage)
            #cursor.insertImage(uuid)
            #return

        super(TextEdit, self).insertFromMimeData(source)
Ejemplo n.º 5
0
#build image attributes
image = ET.Element('image')
stack = ET.SubElement(image, 'stack')
oraxml = image.attrib
oraxml['w'] = str(outimagewidth)
oraxml['h'] = str(outimageheight)

#parse layers
imgc = 0
for path in reversed(map):
    tagtype = path.tag
    imgc = imgc + 1
    if tagtype == 'layer':
        #create canvas image
        canvas = Magick.Image(Magick.Geometry(outimagewidth, outimageheight),
                              "transparent")
        canvas.magick('PNG')
        gidarray = getTMXlayerData(path)
        for y in range(0, height):
            for x in range(0, width):
                Gid = x + (width * y)
                Tid = int(gidarray[Gid])
                if Tid != 0:
                    TidX = (Tid * tilewidth %
                            tilesetimgwidth) - tilewidth  #why need's -32?
                    TidY = ((Tid / (tilesetimgwidth / tilewidth)) *
                            tileheight % tilesetimgheight)
                    PosX = x * tilewidth
                    PosY = y * tileheight
                    tsi = Magick.Image(Magick.Blob(tilesetimageraw))
Ejemplo n.º 6
0
    img.fontPointsize(initialPointsize)
    img.fillColor(fontcolor)
    metric = PythonMagick.TypeMetric()
    img.fontTypeMetrics(word, metric)

    while metric.textWidth() > 100:
        initialPointsize -= 5
        img.fontPointsize(initialPointsize)
        img.fontTypeMetrics(word, metric)
    print(metric.textWidth(), '    ', metric.textHeight())
    # if int(math.floor(abs(random.gauss(0, 1)))) > 0.8:
    #     img.strokeColor(fontcolor)
    #     img.strokeWidth(2)

    # img.annotate(word, PythonMagick.Geometry(10, 4))
    geo = PythonMagick.Geometry('100x32')
    img.annotate(word, geo, PythonMagick.GravityType.CenterGravity, rotateX)

    if int(math.floor(abs(random.gauss(0, 1)))) > 1:
        underline = ''
        for i in range(wordLength):
            underline += '_'
        img.annotate(underline, geo, PythonMagick.GravityType.CenterGravity,
                     rotateX)

    # 这就是下划线
    # -------------------------------------------------------------------

    img.colorSpace(PythonMagick.ColorspaceType.GRAYColorspace)
    # -----------------------save image----------------------------------
    img.magick('jpg')
Ejemplo n.º 7
0
    for i in colorString:
        color += [int(i)]
    for i in range(len(color)):
        color[i] = math.floor(color[i] / 255 * 65535)
    color1 = color[0:3]
    color2 = color[3:6]
    color3 = color[6:9]
    # -------------------------------------------------------------

    # ---------------get the base layer texture-------------------------------
    Scenes = pathwalk('.\SceneData\\')
    randomScene = random.choice(Scenes)
    randomScene = randomScene[0] + randomScene[1]

    randomSceneImage = PythonMagick.Image(randomScene)
    randomSceneGeo = PythonMagick.Geometry(randomSceneImage.size())
    widthRange = randomSceneGeo.width() - 100
    heightRange = randomSceneGeo.height() - 32

    cutGeo = PythonMagick.Geometry('100x32+' +
                                   str(random.randint(0, widthRange)) + '+' +
                                   str(random.randint(0, heightRange)))
    randomSceneImage.crop(cutGeo)
    # randomSceneImage.write('cutOutImage.jpg')
    # ------------------------------------------------------------------

    # --------create the base layer, base texture + base color----------
    baseImage = PythonMagick.Image(
        '100x32', PythonMagick.Color(color1[0], color1[1], color1[2]))
    # baseImage.write('baseColor.jpg')
    baseImage.composite(randomSceneImage, 0, 0,
Ejemplo n.º 8
0
import PythonMagick
n = 1
for i in range(n):
    image = PythonMagick.Image("{}.jpg".format(i))
    image.crop(PythonMagick.Geometry(1500, 1000, 0, 00)) # w, h, x, y
    image.write('{}.tooth.jpg'.format(i))

Ejemplo n.º 9
0
# https://learn.pimoroni.com/tutorial/sandyj/getting-started-with-inky-phat
from inky import InkyWHAT
#inky_display = InkyWHAT("red")
inky_display = InkyWHAT("black")
inky_display.set_border(inky_display.WHITE)
#inky_display.show()
width = 400
height = 300

#img = Image.open("x.png")
#img = Image.open("time.png")

import make_clock
import PythonMagick # sudo apt install -y imagemagick python3-pythonmagick
import PIL # sudo apt install -y python3-willow
resolution = PythonMagick.Geometry(width, height)
import time
import datetime
#composite -size 400x300 -resize 400x300 -gravity center time.svg canvas:white time.png
# from https://stackoverflow.com/a/6209894/5728815
import inspect
import os
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
#print(path)

#while /bin/true; do ./clock.py ; sleep 60; done
make_clock.set_width(width)
make_clock.set_height(height)
palette = PythonMagick.Image(path + "/palette.png")
Ejemplo n.º 10
0
tooth_id = 0

for i in range(n):
    imagePath = "{}.jpg".format(i)
    print 'working for {}'.format(imagePath)
    
    print 'reading image'
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    print 'detecting face'
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.4,
        minNeighbors=5,
        minSize=(30, 30)
        #flags = cv2.CV_HAAR_SCALE_IMAGE
    )

    print("Found {0} faces!".format(len(faces)))

    print 'cropping faces'
    for (x, y, w, h) in faces:
        image = PythonMagick.Image(imagePath)

        image.crop(PythonMagick.Geometry(int(w), int(h/2), int(x), int(y+ h/2))) # w, h, x, y

        image.write('{}.tooth.jpg'.format(tooth_id))
        tooth_id += 1

Ejemplo n.º 11
0
for jpg in jpgfiles:
    img = Magick.Image(dirin.rstrip('/') + "/" + jpg)
    pre_suff = jpg.split(".")

    if args.flipflop == True:
        img.flip()
        img.write(outdir + pre_suff[0] + "_FLIPPED." + pre_suff[1])
        img.flop()
        img.write(outdir + pre_suff[0] + "_FLIPPED_FLOPPED." + pre_suff[1])
        img.flip()
        img.write(outdir + pre_suff[0] + "_FLOPPED." + pre_suff[1])
        img.flop()

    if args.rotate:
        img.rotate(args.rotate)
        img.crop(Magick.Geometry(220, 298, 0, 0))
        img.sample(str(220) + "x" + str(298) + "!")
        img.write(outdir + pre_suff[0] + "_ROTATED" + str(args.rotate) + "." +
                  pre_suff[1])
        img = Magick.Image(dirin.rstrip('/') + "/" + jpg)

    if args.complementary == True:
        img.negate()
        img.write(outdir + pre_suff[0] + "_COMPLEMENT." + pre_suff[1])
        img.negate()

    if args.grayscale == True:
        img.colorSpace(Magick.ColorspaceType.GRAYColorspace)
        img.write(outdir + pre_suff[0] + "_GRAYSCALE." + pre_suff[1])
        img = Magick.Image(dirin.rstrip('/') + "/" + jpg)
Ejemplo n.º 12
0
def work():
    for j in range(50):
        colorString = random.choice(result)
        color = []
        for i in colorString:
            color += [int(i)]
        for i in range(len(color)):
            color[i] = math.floor(color[i] / 255 * 65535)
        color1 = color[0:3]
        color2 = color[3:6]
        color3 = color[6:9]
        # -------------------------------------------------------------

        # ---------------get the base layer texture-------------------------------
        Scenes = pathwalk('.\SceneData\\')
        randomScene = random.choice(Scenes)
        randomScene = randomScene[0] + randomScene[1]

        randomSceneImage = PythonMagick.Image(randomScene)
        randomSceneGeo = PythonMagick.Geometry(randomSceneImage.size())
        widthRange = randomSceneGeo.width() - 100
        heightRange = randomSceneGeo.height() - 32

        cutGeo = PythonMagick.Geometry('100x32+' +
                                       str(random.randint(0, widthRange)) +
                                       '+' +
                                       str(random.randint(0, heightRange)))
        randomSceneImage.crop(cutGeo)
        # randomSceneImage.write('cutOutImage.jpg')
        # ------------------------------------------------------------------

        # --------create the base layer, base texture + base color----------
        baseImage = PythonMagick.Image(
            '100x32', PythonMagick.Color(color1[0], color1[1], color1[2]))
        # baseImage.write('baseColor.jpg')
        baseImage.composite(randomSceneImage, 0, 0,
                            PythonMagick.CompositeOperator.BlendCompositeOp)
        # baseImage.write('mixture.jpg')
        baseImage.xResolution = 96
        baseImage.yResolution = 96
        baseImage.blur(4, 10)
        # ------------------------------------------------------------------

        # -------------generate font----------------------------------------
        # word = python2access.randomWords()
        word = 'F**K'
        fonts = pathwalk('.\\fonts\\font_en\\')
        randomFont = random.choice(fonts)
        randomFont = randomFont[0] + randomFont[1]

        initialPointsize = 45

        baseImage.font(randomFont)
        fontcolor = PythonMagick.Color(color2[0], color2[1], color2[2])

        wordLength = len(word)

        tmp = int(math.floor(abs(random.gauss(0, 1)) * 6))
        if random.randint(1, 2) == 1:
            rotateX = random.randint(0, tmp)
        else:
            rotateX = random.randint(360 - tmp, 360)
        # ------------------------------------------------------------------

        # -------------------generate suitable FontPointsize----------------
        baseImage.fontPointsize(initialPointsize)
        metric = PythonMagick.TypeMetric()
        baseImage.fontTypeMetrics(word, metric)

        while metric.textWidth() > 100 or metric.textHeight() > 36:
            initialPointsize -= 5
            baseImage.fontPointsize(initialPointsize)
            baseImage.fontTypeMetrics(word, metric)
        # ------------------------------------------------------------------

        # -----------------generate shadow/border----------------------------------
        if random.random() > 0.5:
            baseImage.strokeColor(
                PythonMagick.Color(color3[0], color3[1], color3[2]))
            baseImage.strokeWidth(math.ceil(initialPointsize / 10) - 1)
        else:
            addx = math.ceil(random.gauss(0, 2))
            addy = math.ceil(random.gauss(0, 2))
            if addx >= 0:
                addx = '+' + str(addx)
            else:
                addx = str(addx)
            if addy >= 0:
                addy = '+' + str(addy)
            else:
                addy = str(addy)
            # print(addx+addy)
            geoShadow = PythonMagick.Geometry('100x32' + addx + addy)
            addToPointsize = math.floor(abs(random.gauss(0, 1)))
            # print('addToPointsize = ', addToPointsize)
            baseImage.fontPointsize(initialPointsize + addToPointsize)
            baseImage.fillColor(PythonMagick.Color('black'))
            baseImage.annotate(word, geoShadow,
                               PythonMagick.GravityType.CenterGravity, rotateX)
        # ------------------------------------------------------------------

        # -----------------print word---------------------------------------
        baseImage.fontPointsize(initialPointsize)
        baseImage.fillColor(fontcolor)
        geo = PythonMagick.Geometry('100x32')
        baseImage.annotate(word, geo, PythonMagick.GravityType.CenterGravity,
                           rotateX)
        # ------------------------------------------------------------------

        # -----------------underline----------------------------------------
        if int(math.floor(abs(random.gauss(0, 1)))) > 2:
            underline = ''
            for i in range(wordLength):
                underline += '_'
            baseImage.annotate(underline, geo,
                               PythonMagick.GravityType.CenterGravity, rotateX)
        # ------------------------------------------------------------------

        # ------------------------GREYColorSpace----------------------------
        baseImage.colorSpace(PythonMagick.ColorspaceType.GRAYColorspace)
        # ------------------------------------------------------------------

        baseImage.magick('jpg')
        # print(word)
        baseImage.write('.\photo\\' + str(j + 1) + '.jpg')
Ejemplo n.º 13
0
def create_image(filename: str, width: int) -> str:
    geometry = PythonMagick.Geometry(int(width), int(width * 3 / 4))
    color = PythonMagick.Color("Black")
    image = PythonMagick.Image(geometry, color)
    image.write(filename)
    return filename
def CompileFlag(sourcepath, destFolder):
    if not destFolder: destFolder = "output/"
    filename = os.path.splitext(os.path.basename(sourcepath))[0]

    image = PythonMagick.Image(sourcepath)
    imagetype = image.type

    nonecolor = PythonMagick.Color(1 * MaxRGB, 0, 0, 255 * MaxRGB)
    canvas = PythonMagick.Image(PythonMagick.Geometry(128, 128), nonecolor)
    canvas.type = imagetype

    dropshadow = PythonMagick.Image(PythonMagick.Geometry(128, 128), nonecolor)
    dropshadow.type = imagetype

    image = PythonMagick.Image(sourcepath)
    image2 = PythonMagick.Image(sourcepath)
    #image2 = PythonMagick.Image(image2)
    #image2 = PythonMagick.Image( PythonMagick.Geometry( image.size().width(), image.size().height()), nonecolor )
    #image2.composite(image, PythonMagick.Geometry(0,0,0,0), op)

    #image.sample("115x73")
    image.transform("115x73")
    image.enhance()

    dropshadow.fillColor(PythonMagick.Color(0, 0, 0, 25 * MaxRGB))
    dropshadow.draw(
        PythonMagick.DrawableRectangle(
            (128 / 2) - (115 / 2) - 1, (128 / 2) - (73 / 2) - 1,
            (128 / 2) + (115 / 2) + 1, (128 / 2) + (73 / 2) + 1))
    dropshadow.blur(5, 5)

    x = int(128 / 2)
    y = int(128 / 2)
    #geom = PythonMagick.Geometry(int(128/2) - int(115/2), int(128/2) - int(73/2) , int(128/2) + int(115/2), int(128/2) + int(73/2))
    geom = PythonMagick.Geometry(0, 0,
                                 int(128 / 2) - int(115 / 2),
                                 int(128 / 2) - int(73 / 2))
    op = PythonMagick.CompositeOperator.OverCompositeOp
    dropshadow.composite(image, geom, op)
    dropshadow.type = imagetype

    dropshadow.write(destFolder + filename + ".dds")

    tiny = PythonMagick.Image(dropshadow)
    tiny.type = imagetype
    tiny.transform("24x24")
    #tiny.sample("!24x24")
    tiny.write(destFolder + "small/" + filename + ".dds")

    mapflag = PythonMagick.Image(PythonMagick.Geometry(256, 256), nonecolor)

    colourFrequencies = ColourSet(image2)
    sortedColours = [(k, colourFrequencies[k]) for k in sorted(
        colourFrequencies, key=colourFrequencies.get, reverse=True)]

    maxIntensity = 0
    minIntensity = 255
    for i in range(10):
        if i >= len(sortedColours): break
        sortedColour = sortedColours[i][0][1:-1].split(',')
        intensity = int(sortedColour[0]) + int(
            1.2 * float(sortedColour[1])) + int(0.5 * float(sortedColour[2]))
        if intensity > maxIntensity:
            maxIntensity = intensity
        if intensity < minIntensity:
            minIntensity = intensity

    for x in range(image2.size().width()):
        for y in range(image2.size().height()):
            c = ColourToRGBArray(image2.pixelColor(x, y))
            intensity = c[0] + (1.2 * float(c[1])) + (0.5 * float(c[2]))
            actualIntensity = (intensity - minIntensity) / (maxIntensity -
                                                            minIntensity)
            if (actualIntensity < 0.0):
                actualIntensity = 0
            elif (actualIntensity > 1.0):
                actualIntensity = 255 * MaxRGB
            else:
                actualIntensity = int(actualIntensity * 255 * MaxRGB)
            newColour = PythonMagick.Color(
                min(actualIntensity + MaxRGB, 255 * MaxRGB), actualIntensity,
                actualIntensity, 1 * MaxRGB)
            image2.pixelColor(x, y, newColour)

    #image2.sample("!186x118")
    image2.transform("186x118")

    dropshadow2 = PythonMagick.Image(PythonMagick.Geometry(256, 256),
                                     nonecolor)
    dropshadow2.type = imagetype
    dropshadow2.fillColor(PythonMagick.Color(0, 0, 0, 25 * MaxRGB))
    dropshadow2.draw(
        PythonMagick.DrawableRectangle(
            (256 / 2) - (186 / 2) - 1, (256 / 2) - (118 / 2) - 1,
            (256 / 2) + (186 / 2) + 1, (256 / 2) + (118 / 2) + 1))
    dropshadow2.blur(10, 10)

    x = int(256 / 2)
    y = int(256 / 2)
    geom = PythonMagick.Geometry(0, 0,
                                 int(256 / 2) - int(186 / 2),
                                 int(256 / 2) - int(118 / 2))
    op = PythonMagick.CompositeOperator.OverCompositeOp
    dropshadow2.composite(image2, geom, op)
    dropshadow2.type = imagetype

    dropshadow2.fillColor(PythonMagick.Color(0, 0, 0, 255 * MaxRGB))
    dropshadow2.strokeColor(
        PythonMagick.Color(255 * MaxRGB, 255 * MaxRGB, 255 * MaxRGB,
                           1 * MaxRGB))
    dropshadow2.strokeWidth(2)
    dropshadow2.draw(
        PythonMagick.DrawableRectangle(
            (256 / 2) - (186 / 2) - 1, (256 / 2) - (118 / 2) - 1,
            (256 / 2) + (186 / 2) + 1, (256 / 2) + (118 / 2) + 1))

    dropshadow2.write(destFolder + "map/" + filename + ".dds")