簡體   English   中英

Python-PHP將base64保存到圖像

[英]Python - PHP save base64 to image

美好的一天。 有人可以幫我解決我的問題嗎? 我是python和php的新手。 我想將base64編碼的圖像發送到我的php服務器。 但是我不知道我的PHP腳本會發生什么。

編碼后的數據正確發送到php腳本,並將newImage.jpg保存到目錄c:/image/newImage.jpg。 但是,當我嘗試預覽newImage.jpg時,它顯示“ Windows Photo Viewer無法打開此圖片,因為該文件似乎已損壞,損壞或太大”。

問題是我如何可以正確保存圖像。 任何意見和建議都非常感謝。

對不起我的英語不好。 謝謝。

PHP腳本:

<?php
    $encodedString = str_replace(' ','+',$_POST['test']);
    $decoded=base64_decode($encodedString);
    file_put_contents('c:/image/1/newImage.JPG',$decoded);
?>

Python腳本:

import urllib
import urllib2
from urllib import urlencode

url = 'http://192.168.5.165/server/php/try2.php'
encoded = urllib.quote(open("c:/image/1.jpg", "rb").read().encode("base64"))

data = {'test': encoded}
encoded_data = urlencode(data)

website = urllib2.urlopen(url, encoded_data)
print website.read()

在您的PHP代碼中,您需要urldecode() $_POST['test'] ,然后base64_decode() 您無需將空格替換為“ +”(反之亦然)。

在Python中,您只需要urlencode() ,也不需要urllib.quote()

因此,您的PHP可以是:

<?php
    $decoded = base64_decode(urldecode($_POST['test']));
    file_put_contents('c:/image/1/newImage.JPG',$decoded);
?>

和您的Python代碼:

import urllib
import urllib2
from urllib import urlencode

url = 'http://192.168.5.165/server/php/try2.php'
encoded = open("c:/image/1.jpg", "rb").read().encode("base64")

data = {'test': encoded}
encoded_data = urlencode(data)

website = urllib2.urlopen(url, encoded_data)
print website.read()

我是一個懶惰的人,但我會在php中幫助更改為

<?php
    $encodedString = str_replace(' ','+',$_POST['test']);
    $decoded=base64_decode($encodedString);
    $decoded=imagecreatefromstring($decoded);
    imagejpg($decoded, "temp.jpg");
    copy("temp.jpg",'c:/image/1/newImage.JPG');
?>

問題很簡單,您正在嘗試將還沒有圖像的對象保存到文件中,因此首先將圖像設置為臨時圖像,然后將其復制到所需的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM