好用的 python 工具集合
图标处理小程序, 妈妈再也不用担心我不会制作图标了
# PythonMargick包可以到Unofficial Windows Binaries for Python Extension Packages下载
import PythonMagick
import os
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
IMAGE_DIR = os.path.abspath(os.path.join(CURRENT_DIR, '../../images'))
def to_ico(img_src, img_tar='icons'):
img = PythonMagick.Image(img_src)
# 这里要设置一下尺寸,不然会报ico尺寸异常错误
img.sample('128x128')
parent_dir, simple_img_src = os.path.split(img_src)
simple_img_src = os.path.splitext(simple_img_src)[0]
img_tar = os.path.join(parent_dir, img_tar)
img_tar = os.path.join(img_tar, simple_img_src)+'.ico'
img.write(img_tar)
if __name__ == '__main__':
img_name = 'a.gif'
img_src = os.path.join(IMAGE_DIR, img_name)
to_ico(img_src)
"""
Tk() 下有个 iconbitmap 可以指定 icon
"""
pdf 转 图片
最近工作中需要把pdf文件转化为图片,想用python来实现,于是在网上找啊找啊找啊找,找了半天,倒是找到一些代码。
1、第一个找到的代码,我试了一下好像是反了,只能实现把图片转为pdf,而不能把pdf转为图片。。。
把图片转成pdf
代码如下:
#!/usr/bin/env python
import os
import sys
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
f = sys.argv[1]
filename = ''.join(f.split('/')[-1:])[:-4]
f_jpg = filename+'.jpg'
print f_jpg
def conpdf(f_jpg):
f_pdf = filename+'.pdf'
(w, h) = landscape(A4)
c = canvas.Canvas(f_pdf, pagesize = landscape(A4))
c.drawImage(f, 0, 0, w, h)
c.save()
print "okkkkkkkk."
conpdf(f_jpg)
2、第二个是文章写的比较详细,可惜的是linux下的代码,所以仍然没用。
3、第三个文章指出有一个库PythonMagick可以实现这个功能,需要下载一个库 PythonMagick-0.9.10-cp27-none-win_amd64.whl 这个是64位的。
这里不得不说自己又犯了一个错误,因为自己从python官网上下载了一个python 2.7,以为是64位的版本,实际上是32位的版本,所以导致python的版本(32位)和下载的PythonMagick的版本(64位)不一致,弄到晚上12点多,总算了发现了这个问题。。。
4、然后,接下来继续用搜索引擎搜,找到很多stackoverflow的问题帖子,发现了2个代码,不过要先下载PyPDF2以及ghostscript模块。
先通过pip来安装 PyPDF2、PythonMagick、ghostscript 模块。
C:\Users\Administrator>pip install PyPDF2
Collecting PyPDF2
Using cached PyPDF2-1.25.1.tar.gz
Installing collected packages: PyPDF2
Running setup.py install for PyPDF2
Successfully installed PyPDF2-1.25.1
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
C:\Users\Administrator>pip install C:\PythonMagick-0.9.10-cp27-none-win_amd64.whl
Processing c:\pythonmagick-0.9.10-cp27-none-win_amd64.whl
Installing collected packages: PythonMagick
Successfully installed PythonMagick-0.9.10
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
C:\Users\Administrator>pip install ghostscript
Collecting ghostscript
Downloading ghostscript-0.4.1.tar.bz2
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\python27\lib\site-packages (from ghostscript)
Installing collected packages: ghostscript
Running setup.py install for ghostscript
Successfully installed ghostscript-0.4.1
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
下面是代码
代码1:
import os
import ghostscript
from PyPDF2 import PdfFileReader, PdfFileWriter
from tempfile import NamedTemporaryFile
from PythonMagick import Image
reader = PdfFileReader(open("C:/deep.pdf", "rb"))
for page_num in xrange(reader.getNumPages()):
writer = PdfFileWriter()
writer.addPage(reader.getPage(page_num))
temp = NamedTemporaryFile(prefix=str(page_num), suffix=".pdf", delete=False)
writer.write(temp)
print temp.name
tempname = temp.name
temp.close()
im = Image(tempname)
#im.density("3000") # DPI, for better quality
#im.read(tempname)
im.write("some_%d.png" % (page_num))
os.remove(tempname)
代码2:
import sys
import PyPDF2
import PythonMagick
import ghostscript
pdffilename = "C:\deep.pdf"
pdf_im = PyPDF2.PdfFileReader(file(pdffilename, "rb"))
print '1'
npage = pdf_im.getNumPages()
print('Converting %d pages.' % npage)
for p in range(npage):
im = PythonMagick.Image()
im.density('300')
im.read(pdffilename + '[' + str(p) +']')
im.write('file_out-' + str(p)+ '.png')
#print pdffilename + '[' + str(p) +']','file_out-' + str(p)+ '.png'
然后执行时都报错了,这个是 代码2 的报错信息:
Traceback (most recent call last):
File "C:\c.py", line 15, in <module>
im.read(pdffilename + '[' + str(p) +']')
RuntimeError: pythonw.exe: PostscriptDelegateFailed `C:\DEEP.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/713
总是在上面的 im.read(pdffilename + '[' + str(p) +']') 这一行报错。
于是,根据报错的信息在网上查,但是没查到什么有用的信息,但是感觉应该和GhostScript有关,于是在网上去查安装包,找到一个在github上的下载连接,但是点进去的时候显示无法下载。
最后,在csdn的下载中找到了 这个文件:GhostScript_Windows_9.15_win32_win64,安装了64位版本,之后,再次运行上面的代码,都能用了。
不过代码2需要做如下修改,不然还是会报 No such file or directory @ error/pdf.c/ReadPDFImage/713 错误:
#代码2
import sys
import PyPDF2
import PythonMagick
import ghostscript
pdffilename = "C:\deep.pdf"
pdf_im = PyPDF2.PdfFileReader(file(pdffilename, "rb"))
print '1'
npage = pdf_im.getNumPages()
print('Converting %d pages.' % npage)
for p in range(npage):
im = PythonMagick.Image(pdffilename + '[' + str(p) +']')
im.density('300')
#im.read(pdffilename + '[' + str(p) +']')
im.write('file_out-' + str(p)+ '.png')
#print pdffilename + '[' + str(p) +']','file_out-' + str(p)+ '.png'
这次有个很深刻的体会,就是解决这个问题过程中,大部分时间都是用在查资料、验证资格资料是否有用上了,搜索资料的能力很重要。
而在实际搜索资料的过程中,国内关于PythonMagick的文章太少了,搜索出来的大部分有帮助的文章都是国外的,但是这些国外的帖子文章,也没有解决我的问题或者是给出有用的线索,最后还是通过自己的思考,解决了问题。
批量修改图片大小 (mb)
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
author : 蛙鳜鸡鹳狸猿
create_time : 2016年 11月 01日 星期二 17:38:06 CST
program : *_* script of resizing image *_*
"""
import sys
import PythonMagick
class ManImage:
"""
Manipulate Image Object
"""
def __init__(self, i_file, o_dire):
"""
init args
:param i_file: (str) input image file (eg: "/home/img.jpg")
:param o_dire: (str) output image directory (eg: "/home/")
"""
self.i_file = i_file
self.o_dire = o_dire
def __str__(self):
traceback = "Executing under {0.argv[0]} of {1.i_file} into {2.o_dire}......".format(sys, self, self)
return traceback
def playimage(self, rs):
"""
resize image file
:param rs: (int) set rs = 400 ~= 100KB output under my test
:return: resized PNG image file
"""
image = PythonMagick.Image(self.i_file)
try:
image.resize(str(rs))
image.monochrome(True)
image.magick("PNG")
image.write(self.o_dire + self.i_file.split('/')[-1].split('.')[0] + '.png')
print('"{0.i_file}" play OK......'.format(self))
except Exception, e:
print(str(e))
以上代码写入一个“class_image.py”文件,下面是调取的简单示例。
# !/usr/bin/python
# -*- coding: utf-8 -*-
# te_author : 蛙鳜鸡鹳狸猿
# create_time : 2016年 11月 01日 星期二 17:38:06 CST
# NOTICE : *_* script of resizing image to set*_*
import os
import sys
import class_image
i_dire = sys.argv[1]
o_dire = sys.argv[2]
rs = sys.argv[3]
for i_file in os.listdir(i_dire):
class_image.ManImage(i_file=i_dire + i_file, o_dire=o_dire).playimage(rs=rs)
即在命令行分别传入读入目录、输出目录以及图片大小三个参数,操作起来方便简捷。图片可以直接从pdf文件里面逐页转换出来并同时修改图片大小,参考:http://blog.csdn.net/sweeper_freedoman/article/details/53000145。如果已经安装使用“ImageMagick”,也可以通过Python调用处理图片,参考http://blog.csdn.net/sweeper_freedoman/article/details/69789307。
链接地址
好用的 python 工具集合的更多相关文章
- python爬虫工具集合
python爬虫工具集合 大家一起来整理吧!强烈建议PR.这是初稿,总是有很多问题,而且考虑不全面,希望大家支持! 源文件 主要针对python3 常用库 urllib Urllib是python提供 ...
- 统计和分析系统性能【IO CPU 内存】的工具集合
统计和分析系统性能[IO CPU 内存]的工具集合 blktrace http://www.oschina.net/p/blktrace 获取磁盘写入的信息 root@demo:~/install/p ...
- linux shell工具集合
1)判断进程是否存在,如果不存在再执行启动命令,可以避免一个脚本同时启动多份 if [ $(ps -ef |grep bastion_account.sh|grep -v grep|wc -l) - ...
- 数据分析常用的python工具和SQL语句
select symbol, "price.*" from stocks :使用正则表达式来指定列查询 select count(*), avg(salary) from empl ...
- Python工具库分享
漏洞及渗透练习平台: WebGoat漏洞练习平台: https://github.com/WebGoat/WebGoat webgoat-legacy漏洞练习平台: https://github.co ...
- ETH&EOS开发资源及工具集合(完整汇总版)
ETH&EOS开发资源及工具集合(完整汇总版) 3113 ETH开发资源篇 一.开发语言 · Solidity - 官方推荐以太坊智能合约开发语言,也是目前最为主流的智能合约语 ...
- Python工具库(感谢backlion整理)
漏洞及渗透练习平台: WebGoat漏洞练习平台: https://github.com/WebGoat/WebGoat webgoat-legacy漏洞练习平台: https://github.co ...
- 专为渗透测试人员设计的 Python 工具大合集
如果你对漏洞挖掘.逆向工程分析或渗透测试感兴趣的话,我第一个要推荐给你的就是Python编程语言.Python不仅语法简单上手容易,而且它还有大量功能强大的库和程序可供我们使用.在这篇文章中,我们会给 ...
- sublime开发php必备工具集合(mac)
sublime开发php必备工具集合(Mac) 相关链接:http://benmatselby.github.io/sublime-phpcs/ 目标: 直接在sublime中运行php代码 按PSR ...
随机推荐
- grep命令和tail命令
写在前面的话: 最近参与了新项目开发,周期短,与自己负责的主要业务对接.业务复杂,时常出现bug,然额对于菜鸟的我,更是无从下手.其实最好的帮助就是 学会查看日志,关键是之前查看日志真是太少了,菜鸟一 ...
- Android SDK更新后Eclipse无法正常工作问题
一,问题描述 更新完Android SDK后,如果你的ADT版本低于其设定的最新版本,你更新完后立马会报错 这个时候你的项目出现各种红线,反正看着让人很不爽 二,原因 每次你更新完SDK后,Andro ...
- stm8问题记录
sprintf 错误 现象:打印不出来数字 需要包含#include<stdio.h>
- GitHub:Alibaba
ylbtech-GitHub:Alibaba 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 5.返回顶部 1. https://github.com/alibaba 2. ...
- CMD(命令提示符)-------javac编译程序出现“”编码GBK的不可映射字符“”
问题描述:使用命令提示符(CMD)编译写好的java程序的时候出现“编码GBK的不可映射字符” 问题截图: 问题分析:看提示就知道是代码的注释出现问题,但注释格式完全正确,那么问题就只可能是注释编码出 ...
- 使用MJRefresh自定义下拉刷新,上拉加载动画
有时候我们需要自己设置下拉刷新,上拉加载动画的实现,这里主要是记录下使用MJRefresh自定义下拉刷新,上拉加载动画..... 下拉刷新我们只需要继承MJRefreshGifHeader即可: 实现 ...
- 【HANA系列】SAP HANA SQL从给定日期中获取月份
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[HANA系列]SAP HANA SQL从给定日 ...
- python学习之数据类型(int,bool,str)
第三章 数据类型 3.1 Python基本数据类型 类型 含义 描述 int 整数 主要用来进⾏数学运算 str 字符串 可以保存少量数据并进⾏相应的操作 bool 布尔值 判断真假,True,Fal ...
- Django视图之FBV与CBV
一. CBV与FBV CBV:Class Based View FBV:Function Based View 我们之前写过的都是基于函数的view,就叫FBV.还可以把view写成基于类的,那就是C ...
- Linux C/C++基础——二级指针做形参
1.二级指针做形参 #include<stdio.h> #include<stdlib.h> void fun(int **temp) { *temp=(int*)malloc ...