def convert_with_cairosvg_sizes(width, height, file, outfile): from cairosvg.surface import PNGSurface with open(file, 'rb') as svg_file: PNGSurface.convert(bytestring=svg_file.read(), width=width, height=height, write_to=open(outfile, 'wb'))
def convert_with_cairosvg_sizes(file_svg, file_png): from cairosvg.surface import PNGSurface with open(file_svg, 'rb') as svg_file: PNGSurface.convert(bytestring=svg_file.read(), width=512, height=512, write_to=open(file_png, 'wb'))
def draw_layer(self, image): try: dc = wx.MemoryDC() dc.SelectObject(self.bitmap) dc.SetBackground(wx.Brush("black")) dc.Clear() if self.slicer == "Slic3r" or self.slicer == "Skeinforge": if self.scale != 1.0: layercopy = copy.deepcopy(image) height = float(layercopy.get("height").replace("m", "")) width = float(layercopy.get("width").replace("m", "")) layercopy.set("height", str(height * self.scale) + "mm") layercopy.set("width", str(width * self.scale) + "mm") layercopy.set("viewBox", "0 0 " + str(width * self.scale) + " " + str(height * self.scale)) g = layercopy.find("{http://www.w3.org/2000/svg}g") g.set("transform", "scale(" + str(self.scale) + ")") stream = cStringIO.StringIO( PNGSurface.convert(dpi=self.dpi, bytestring=xml.etree.ElementTree.tostring(layercopy)) ) else: stream = cStringIO.StringIO( PNGSurface.convert(dpi=self.dpi, bytestring=xml.etree.ElementTree.tostring(image)) ) pngImage = wx.ImageFromStream(stream) # print "w:", pngImage.Width, ", dpi:", self.dpi, ", w (mm): ",(pngImage.Width / self.dpi) * 25.4 if self.layer_red: pngImage = pngImage.AdjustChannels(1, 0, 0, 1) dc.DrawBitmap(wx.BitmapFromImage(pngImage), self.offset[0], self.offset[1], True) elif self.slicer == "bitmap": if isinstance(image, str): image = wx.Image(image) if self.layer_red: image = image.AdjustChannels(1, 0, 0, 1) dc.DrawBitmap( wx.BitmapFromImage(image.Scale(image.Width * self.scale, image.Height * self.scale)), self.offset[0], -self.offset[1], True, ) else: raise Exception(self.slicer + " is an unknown method.") self.pic.SetBitmap(self.bitmap) self.pic.Show() self.Refresh() except: raise pass
def convert_svg_to_png(self, svg_bytes, width, height, output_path): if os.path.isfile(output_path): return PNGSurface.convert( bytestring=svg_bytes, width=width, height=height, write_to=open(output_path, 'wb'), )
def convert_with_cairosvg_sizes(args): from cairosvg.surface import PNGSurface width, height = args.size.split('x') with open(args.file, 'rb') as svg_file: PNGSurface.convert( bytestring=svg_file.read(), width=width, height=height, write_to=open(args.out, 'wb') )
def svg2png_transparent_background(svg_name, args): # import pdb;pdb.set_trace() png_name = svg_name.replace(".svg", '.png') with open(svg_name, 'rb') as svg_file: PNGSurface.convert( bytestring=svg_file.read(), write_to=open(png_name, 'wb'), output_width=int(args.width), output_height=int(args.height), ) os.remove(svg_name)
def main(): parser = argparse.ArgumentParser() parser.add_argument('--ppmm', help="Pixels per mm", default=1, type=int) parser.add_argument("svg_filename") args = parser.parse_args() s = SVGSplitter(args.svg_filename, args.ppmm) print("Number of layers: %d" % s.num_layers()) i = 0 for l in s.layer_generator(): PNGSurface.convert(bytestring=l, write_to="%d.png" % i) i += 1
def svg_image_factory(fp, filename): mime_type = magic.from_buffer(fp.read(1024), mime=True) if mime_type != "image/svg+xml": raise TypeError fp.seek(0) png_data = PNGSurface.convert(fp.read(), url_fetcher=url_fetcher) return PngImageFile(BytesIO(png_data))
def energy_path(self): stemfn = "energy" svg = self.factory.render(self.state) png = PNGSurface.convert(bytestring=str(svg)) png = StringIO.StringIO(png) scores = self.compare.compare(png) energy = scores[0] self.step_callback(energy) return energy
def draw_layer(self, image): try: dc = wx.MemoryDC() dc.SelectObject(self.bitmap) dc.SetBackground(wx.Brush("black")) dc.Clear() if self.slicer == 'Slic3r' or self.slicer == 'Skeinforge': if self.scale != 1.0: image = copy.deepcopy(image) height = float(image.get('height').replace('m', '')) width = float(image.get('width').replace('m', '')) image.set('height', str(height * self.scale) + 'mm') image.set('width', str(width * self.scale) + 'mm') image.set( 'viewBox', '0 0 ' + str(width * self.scale) + ' ' + str(height * self.scale)) g = image.find("{http://www.w3.org/2000/svg}g") g.set('transform', 'scale(' + str(self.scale) + ')') pngbytes = PNGSurface.convert( dpi=self.dpi, bytestring=xml.etree.ElementTree.tostring(image)) pngImage = wx.Image(io.BytesIO(pngbytes)) #print("w:", pngImage.Width, ", dpi:", self.dpi, ", w (mm): ",(pngImage.Width / self.dpi) * 25.4) if self.layer_red: pngImage = pngImage.AdjustChannels(1, 0, 0, 1) dc.DrawBitmap(wx.Bitmap(pngImage), self.offset[0], self.offset[1], True) elif self.slicer == 'bitmap': if isinstance(image, str): image = wx.Image(image) if self.layer_red: image = image.AdjustChannels(1, 0, 0, 1) bitmap = wx.Bitmap( image.Scale(image.Width * self.scale, image.Height * self.scale)) dc.DrawBitmap(bitmap, self.offset[0], -self.offset[1], True) else: raise Exception(self.slicer + " is an unknown method.") self.pic.SetBitmap(self.bitmap) self.pic.Show() self.Refresh() except: raise pass
def svg2png(in_path, width, height, out_path): with open(in_path, 'rb') as svg_file: png = PNGSurface.convert(bytestring=svg_file.read(), width=width, height=height) image = np.array(Image.open(io.BytesIO(png)))[:, :, -1] image = Image.fromarray(image) w, h = image.size ratio = w / float(h) new_im = Image.new("L", (64, 64)) new_size = (w * 64 // h, 64) image = image.resize(new_size, Image.ANTIALIAS) new_im.paste(image.convert('L'), ((64 - new_size[0]) // 2, (64 - new_size[1]) // 2)) plt.imsave(out_path, new_im)
def svgtopil(self, svg): '''converts SVG snippets to a PIL Image ''' tree = xml.etree.ElementTree.parse(svg) root = tree.getroot() dpi = 25.4 / self.params['samplegridsize'] bytestring = BytesIO( PNGSurface.convert(bytestring=xml.etree.ElementTree.tostring(root), dpi=dpi)) img = Image.open(bytestring) # following is done to fix issue with transparent backgrounds img = img.convert('RGBA') # PIL doesn't support 2 bit images new_image = Image.new("RGBA", img.size, "WHITE") img.paste(new_image, mask=img) # img.save('test.png') return img
def svg_image_factory(data, *args): png_data = PNGSurface.convert(data.read()) return PngImageFile(BytesIO(png_data))
def _bookVaccine(self, session, vaccineCenter): if int(datetime.datetime.now().timestamp()) > jwt.decode(self.token, options={"verify_signature": False})["exp"]: print("\n") self.sendOtp() os.system(f'telegram-send "Enter OTP on terminal! | {str(datetime.datetime.today())}" &') self.confirmOtp() # /auth/getRecaptcha # /appointment/schedule captcha = requests.post(BASEURL+"/auth/getRecaptcha", data=json.dumps({}), headers={**HEADERS, **{"authorization": f"Bearer {self.token}"}}) with open("captcha.svg", "w") as f: f.write(eval(captcha.text)['captcha']) with open("captcha.svg", 'rb') as f: PNGSurface.convert(bytestring = f.read(), write_to = open("captcha.png", 'wb')) os.system(f"telegram-send -i captcha.png &") while True: self.captchaInput = input("Enter Captcha: ") if self.captchaInput: break p = { "dose": 1, "session_id": session["session_id"], "center_id": int(vaccineCenter['center_id']), "slot": session["slots"][-1], "beneficiaries": [self.familyMembers[x]['beneficiary_reference_id'] for x in self.selectedFamilyMembers], "captcha": self.captchaInput } r = requests.post(BASEURL+"/appointment/schedule", data=json.dumps(p), headers={**HEADERS, **{"authorization": f"Bearer {self.token}"}}) if r.status_code == 200: self.isVaccineBooked = True self.appointment_id = eval(r.text)['appointment_confirmation_no'] for member in self.selectedFamilyMembers: template = f"""Vaccine Booked for Appointment ID -> {self.appointment_id} Vaccine -> {session['vaccine']} Date/Time -> {session['date']} {session['slots'][-1]} Center -> {vaccineCenter['name']} {vaccineCenter['address']}""".replace(" ","") print(template) templateForTelegram = f"Dear {member['name']}, Your vaccination is scheduled for {session['date']} {session['slots'][-1]} at {vaccineCenter['name']} {vaccineCenter['address']}, Your booking reference ID is {member['beneficiary_reference_id']} and your 4 digit secret code for vaccination is {member['beneficiary_reference_id'][member['beneficiary_reference_id']-4:]}. Your vaccine is {session['vaccine']} and your appointment ID is {self.appointment_id}." os.system(f"telegram-send \"{templateForTelegram}\" &") appointmentSlipRequest = requests.get(BASEURL + f"/appointment/appointmentslip/download?appointment_id={self.appointment_id}", headers={**HEADERS, **{"authorization": f"Bearer {self.token}"}}) with open("Appointment_Slip.pdf", "wb") as f: f.write(appointmentSlipRequest.content) os.system("telegram-send --file Appointment_Slip.pdf &") else: print(r.status_code, r.text) self.isVaccineBooked = False