[英]Encode Base64 Django ImageField Stream
I receive an Image through my form, which I not want to save as usual in a FileField
but in a CharField
as Base64. 我通过表单收到一个图像,我不想像往常一样将其保存在FileField
而是在CharField
为Base64。 This is my current setup: 这是我当前的设置:
models.py models.py
class Image(models.Model):
company = models.ForeignKey(Company)
img = models.TextField()
img_id = models.CharField(blank=True, null=True, max_length=64)
img_class = models.CharField(blank=True, null=True, max_length=64)
created = models.DateField(auto_now_add=True, editable=False)
forms.py 表格
class ImageForm(forms.Form):
img = forms.ImageField()
img_id = forms.CharField(required=False)
img_class = forms.CharField(required=False)
views.py views.py
class ImageUploadView(LoginRequiredMixin, FormView):
form_class = ImageForm
template_name = "upload.html"
success_url = reverse_lazy("home")
def form_valid(self, form):
account = Account.objects.get(user=self.request.user)
html = Html.objects.get(company=account.company)
if self.request.user.is_authenticated():
company = Company.objects.get(account=account)
form_img = form.cleaned_data['img']
print(form_img.__dict__.keys())
print(form_img.image)
return super(ImageUploadView, self).form_valid(form)
The output of print(form_img.__dict__.keys())
is print(form_img.__dict__.keys())
是
['file', 'content_type_extra', 'image', 'charset', '_name', 'content_type', '_size', 'field_name']
and the output of print(form_img.image)
for an Png Image is: Png图像的print(form_img.image)
输出为:
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=183x161 at 0x7F087B2E6B90>
and for an JPG it is: 对于JPG,它是:
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x400 at 0x7F087B16EC50>
Is it possible to encode the received image as base64 and save it into the database from stream and with out temporarily saving it somewhere? 是否可以将接收到的图像编码为base64并从流中将其保存到数据库中,而无需将其临时保存在某个地方?
Edit: got it working now! 编辑:现在就可以工作了!
b64_img = base64.b64encode(form_img.file.read())
That was basically everything! 基本上就是一切!
Yes it's possible to do it easily with PIL ! 是的,使用PIL可以轻松做到这一点!
Save image in the buffer and encode it in base64. 将图像保存在缓冲区中,并在base64中进行编码。
import base64
import cStringIO
img_buffer = cStringIO.StringIO()
image.save(img_buffer, format="imageFormatYouWant")
img_str = base64.b64encode(img_buffer.getvalue())
with open("yourImage.ext", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.