方法1:pillow將多張圖片顯示在一張畫布上
缺點:每張畫布上圖片個數必須是給定數量
class MakeCodeAction(BaseActionView): # 這里需要填寫三個屬性 action_name = "create_assets_qr_code" description = u'Create selected IT二維碼' model_perm = 'change' def do_action(self,queryset): img_list = [] for obj in queryset: code_str = 'http://{url}/assets/decode_code/?num={OYcode}'.format(url=self.request.META['HTTP_HOST'], OYcode=obj.num) filename = CreateCode().make_code(text=code_str) img_list.append(filename) IMAGE_SIZE = 256 # 每張小圖片的大小 IMAGE_ROW = 5 # 圖片間隔,也就是合並成一張圖后,一共有幾行 IMAGE_COLUMN = 4 # 圖片間隔,也就是合並成一張圖后,一共有幾列 IMAGE_SAVE_PATH = 'media/qrcode_all/{}.png'.format(uuid.uuid4().hex[4:]) # 圖片轉換后的地址 # 簡單的對於參數的設定和實際圖片集的大小進行數量判斷 if len(img_list) != IMAGE_ROW * IMAGE_COLUMN: raise ValueError("合成圖片的參數和要求的數量不能匹配!") # 定義圖像拼接函數 import PIL.Image as Image # def image_compose(): to_image = Image.new('RGB', (IMAGE_COLUMN * IMAGE_SIZE, IMAGE_ROW * IMAGE_SIZE)) # 創建一個新圖 # 循環遍歷,把每張圖片按順序粘貼到對應位置上 for y in range(1, IMAGE_ROW + 1): for x in range(1, IMAGE_COLUMN + 1): from_image = Image.open(img_list[IMAGE_COLUMN * (y - 1) + x - 1]).resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS) to_image.paste(from_image, ((x - 1) * IMAGE_SIZE, (y - 1) * IMAGE_SIZE)) to_image.save(IMAGE_SAVE_PATH) # 保存新圖 if os.path.exists(IMAGE_SAVE_PATH): qrimg_data = open(IMAGE_SAVE_PATH, 'rb').read() return HttpResponse(qrimg_data, content_type="image/png")
方法2:opencv-pyplot多張圖片顯示在一張圖片上
缺點: 只能橫向或豎向排一列
import cv2 from pylab import * img1 = cv2.imread('logo.jpg',cv2.IMREAD_COLOR) img2 = cv2.imread('logo.jpg',cv2.IMREAD_GRAYSCALE) img3 = cv2.imread('logo.jpg',cv2.IMREAD_UNCHANGED) img4 = cv2.imread('logo.jpg') htitch= np.hstack((img1, img3,img4)) # 橫向排列 vtitch = np.vstack((img1, img3)) # 縱向排列 cv2.imshow("test1",htitch) cv2.imshow("test2",vtitch) cv2.waitKey(0) cv2.destroyAllWindows() ImportError: No module named cv2 安裝:pip2 install opencv-python==4.2.0.32 No module named 'pylab' 安裝:pip2 install matplotlib ERROR: Cannot uninstall 'pyparsing'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. 解決方法是手動重裝最新版 pyparsing sudo pip install -I pyparsing==2.2.0 pip install matplotlib ImportError: No module named Tkinter 安裝: yum install -y tkinter yum install -y tk-devel DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
