How to load Blobproperty image in Google App Engine? - image

I wrote some codes.
I could save image in BobProperty.
But I cannot load image into HTML page...
source code:
class Product(db.Model):
image = db.BlobProperty()
...
class add:
productImage = self.request.get('image')
product.image = db.Blob(productImage)
product.put()
but i wrote {{product.image}} into html code. But there were like ��袀 ���� ���� ���� (����������� ��(:(������� (������� (��>̢��� (�������>������Y������K��׏
What should i do if i want load image from datastore?

I use an auxiliary view:
def serve_image(request, image):
if image == "None":
image = ""
response = HttpResponse(image)
response['Content-Type'] = "image/png"
response['Cache-Control'] = "max-age=7200"
return response
and in the model:
def get_image_path(self):
# This returns the url of serve_image, with the argument of image's pk.
# Something like /main/serve_image/1231234dfg22; this url will return a
# response image with the blob
return reverse("main.views.serve_image", args=[str(self.pk)])
and just use {{ model.get_image_path }} instead.
(this is django-nonrel, but I guess you could figure out what it does)
Also, there is a post here about this; you should check it out.

Related

How do I view both the prediction and the image on the same page in Flask?

I have run a model that predicts whether an image is a lake or an ocean. I have been able to serve this model successfully on my local host where I upload an image and it predicts the class (ocean or lake) as well as the probability/confidence. I can return that result or I can return the image, but for some reason I cannot return both the image and the prediction result.
I have searched stackoverflow and github and tried many different things per the comment code. I can display an image from the web, but I can't display the image that was uploaded. I have read and leveraged code from Github but that only returns the image without the prediction results
from flask import Flask, flash, request, redirect, url_for
import os
from werkzeug import secure_filename
from flask import send_from_directory
UPLOAD_FOLDER = ''
ALLOWED_EXTENSIONS = set(['jpg'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
image = open_image(filename)
image_url = url_for('uploaded_file', filename=filename)
#print(learn.predict(image))
ok = learn.predict(image)
first = round(ok[2].data.tolist()[0], 4)*100
second = round(ok[2].data.tolist()[1], 4)*100
if first > second:
okp = first
else:
okp = second
#return redirect(url_for('uploaded_file', filename=filename)) I can get this to work
#return '''url_for('uploaded_file', filename=filename)'''
#return '''<img src = "{{image}}"/>'''
#return '''<h1>The prediction is: {}</h1><h1>With a confidence of: {}%'''.format(ok[0], okp)
return '''<h1>The prediction is: {}</h1><h1>With a confidence of: {}%</h1>
<img src= "{{image_url}}" height = "85" width="200"/>'''.format(ok[0], okp)
#return '''<img src = "{{send_from_directory(app.config['UPLOAD_FOLDER'], filename)}}"/>'''
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload a jpg of an Ocean or a Lake</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(port=5000, debug=False)
This is what I get:
The prediction is: oceans
With a confidence of: 94.66%
Then the icon of a pic when a pic is not there
I would like to show the image that was uploaded along with the results.
Just put the image_url value in your <img href="..."> attribute:
return '''<h1>The prediction is: {}</h1><h1>With a confidence of: {}%</h1>
<img src="{}" height = "85" width="200"/>'''.format(ok[0], okp, image_url)
You can't use {{image_url}} syntax, that'd require that you used the Jinja2 template feature of Flask.
image_url is the string that you generated for the uploaded_file() view, so the browser knows where to load the image from to fill the <img /> tag in the HTML page.

Grails render-plugin does not render images

I have now setup the render-plugin and I get nice PDF-files but I also need to put an image into a few columns in my table. These images are conditionally selected by a data field of the instance.
I have the image in the assets/images folder as I think is the correct place.
I use the following GSP-line in the template that will be used by the renderer to create the PDF.
<td><g:if test="${od?.priceFSC > 0.1}"><asset:image src="checkOut16x16.png" width="16" height="16"/></g:if></td>
As a HTML-view the images prints perfect but when render the PDF they are missing.
I checked the documentation and tried the code from the example:
The controller:
def createPDF() {
def file = new File("asets/CheckOut16x16.png")
def OfferHeader offerHeader = OfferHeader.get(params.id)
[offerHeader: offerHeader])
renderPdf(template: "/stocknote/Stocknote", model: [offerHeader: offerHeader,imageBytes: file.bytes], filename: "Stocknote-"+params.id+".pdf")
}
The view:
<rendering:inlinePng bytes="${imageBytes}" class="some-class" />
I didn't care of the condition here I just wanted to see if it would be printed but it's not because the view crasched:
URI
/stocknote/editStocknote/32
Class
org.grails.taglib.GrailsTagException
Message
Request processing failed; nested exception is org.grails.gsp.GroovyPagesException: Error processing GroovyPageView: [views/stocknote/editStocknote.gsp:32] [views/stocknote/_StocknoteDetail.gsp:3] 'bytes' is required
Caused by
[views/stocknote/editStocknote.gsp:32] [views/stocknote/_StocknoteDetail.gsp:3] 'bytes' is required
I don't know what I've done wrong but error message seems confusing, "Bytes is required" but I have bytes="${imageBytes}".
Hope someone could give me some help or explanation.
Sounds like the path to your file is incorrect, try:
Controller:
def assetResourceLocator
def createPDF() {
def file = assetResourceLocator.findAssetForURI( 'CheckOut16x16.png' )
def OfferHeader offerHeader = OfferHeader.get(params.id)
[offerHeader: offerHeader])
renderPdf(template: "/stocknote/Stocknote", model: [offerHeader: offerHeader,imageBytes: file.getByteArray()], filename: "Stocknote-"+params.id+".pdf")
}
View should be fine as is.
Made a big mistake >_<, The template used to create the PDF is also used by the view from where you order the PDF and at that time the image has not been created by the controller.
So to come through, I had to check the value of the image before rendering.
<g:if test="${imageBytes!= null}"> <rendering:inlinePng bytes="${imageBytes}" /></g:if>
That what was needed.

grails - access image in controller to use in pdf

I'm creating a dynamic pdf with gsp and I'd like to add an image to it but I have no idea how to do this coz simply using <img src="${resource(dir: 'images/vip', file: 'heading.png')}"/> in the gsp does not seem to work. When creating an email you use inline 'pic1', 'image/jpg', resourceLoader.getResource("/images/bawHeader3.png").getFile() in the .sendMail so I was wondering if it's possible to do something similar for pdf. Here's what I got so far:
def downloadBooking() {
def result = Booking.findById(params.id)
renderPdf(template: "/pdf/booking/vipConfirmation", model : result)
}
The above works fine, I just don't know how to add an image into it. Also please show me how I would access the image inside the gsp please.
You need send the bytecode of image to "pdfRenderingService". here is configuration below.
//convert image to bytecode and pass it to the padf rendring service.
def imageBytes=grailsResourceLocator.findResourceForURI('/images/user.png').file.bytes
Passing the value to pdfrendering service.
ByteArrayOutputStream reportBytes = pdfRenderingService.render(template: "/pdf/booking/vipConfirmation", model: [result: result, "imageBytes": imageBytes])
Accessing image in template
<div> <rendering:inlinePng bytes="${imageBytes}" class="header-img"/> </div>
Grails 3.3.9
import org.springframework.core.io.Resource
def assetResourceLocator
Resource resource = assetResourceLocator.findAssetForURI('logo.png')
ByteArrayOutputStream bytes = pdfRenderingService.render(template: "/pdfs/invoice", model: [imageBytes: resource.getInputStream().bytes]) as ByteArrayOutputStream

Can't get homemade CKEditor file uploader working in web2py

There's something arcane going on with my custom CKEditor uploader. The image or whatever file I try to upload to the server is correctly uploaded but no matter what I do it's link won't show up in the editor. It looks like the callback to CKEditor in my upload_file.html view doesn't work as it should. The documentation of CKEditor is really sparse about these things, so I could really use some guidance here.
In my controller I have the following upload function:
def upload_file():
upload = request.vars.upload
if upload != None:
if hasattr(upload, 'file'):
old_filename = upload.filename
new_filename = db.files.uploaded_data.store(upload.file, upload.filename)
result = db.files.insert(filename = old_filename,
uploaded_data = new_filename,
created_on = datetime.today())
if not result:
message = T('An error has occured during upload.')
url = ''
else:
message = T('File uploaded succesfully.')
url = URL(r = request, f = 'download', args = new_filename)
return dict(form = None, cknum = request.vars.CKEditorFuncNum, url = url, message = message)
else:
raise HTTP(401, T('Upload is not proper type.'))
else:
form = SQLFORM(db.files, fields = ['uploaded_data'])
upload = request.vars.uploaded_data
if upload != None:
form.vars.filename = upload.filename
form.vars.created_on = datetime.today()
if form.process().accepted:
response.flash = T('File uploaded successfully!')
elif form.errors:
response.flash = T('form has errors')
else:
response.flash = T('please fill out the form')
return dict(form = clean_form(form))
The view for this function looks like this:
{{if form != None:}}
{{extend 'layout.html'}}
{{=form}}
{{else:}}
<html>
<body>
<script type="text/javascript">
window.opener.CKEDITOR.tools.callFunction({{=cknum}}, '{{=url}}', '{{=message}}');
</script>
</body>
</html>
{{pass}}
I have a test view with a form containing several textareas all of which are properly converted to editors:
{{extend 'layout.html'}}
<script type="text/javascript">
CKEDITOR.config.filebrowserBrowseUrl = "{{=URL(request.application, c='default', f='upload_file')}}";
CKEDITOR.config.filebrowserUploadUrl = "{{=URL(request.application, c='default', f='upload_file')}}";
CKEDITOR.config.filebrowserWindowHeight = '60%';
CKEDITOR.config.filebrowserWindowWidth = '70%';
</script>
{{=form}}
I finally found the solution. There's a mistake in the view of the upload_file function.
window.opener.CKEDITOR.tools.callFunction({{=cknum}}, '{{=url}}', '{{=message}}');
should be rewritten to this:
window.parent.CKEDITOR.tools.callFunction({{=cknum}}, '{{=url}}', '{{=message}}');
I copied the first version, which caused me quite a lot of headache, from web2pyslices, so I write this answer here in the hope that it will help others trying to integrate CKEditor with Web2py.

how to display images in Grails?

I am trying to render the images from /WEB-INF/images/sps in the GSP page using the following code:
def index = {
def baseFolder = grailsAttributes.getApplicationContext().getResource("/").getFile().toString()
println baseFolder
def imagesFolder = baseFolder + '/images/sps'
println imagesFolder
def imageList1 = new File(imagesFolder).list()
println imageList1
def imageList = Arrays.asList(imageList1)
println imageList
imageList
//redirect(action:"displayImages", params:["imageList":imageList])
//render(view:"displayImages")
}
The controller is able to read the images from the fileSystem. But when I try to display them using the following code, the images are not coming.
index.gsp
<g:each in="${imageList}" var="image">
<img src="${resource(dir: 'images', file: image.filename)}" alt="Grails"/>
</g:each>
What mistake am I doing?
EDIT:
When I try with single image, it is working fine - I am able to view the image that is in the WEB-INF/images folder
<img src="${resource(dir: 'images', file: '1.jpg')}" alt="Grails"/>
And there is no HTML code thats getting generated for the loop code(above index.gsp code). Its just blank.
My requirement is to display all the image files that are on the file system folder.
It was simpler. You should return a model from an action as a Map: [imageList: imageList] for imageList to be available by name in GSP.
And yes, can you move images folder to web-app - is it OK that all the world can request your images via HTTP?
you are returning a list of File objects, where you will call the toString method of the file object which most likely returns the absoute file path of the file object.
this would give you something like this in the html source code
<img src="/app/images/c:\path\to\imagefile.png">
try calling
<img src="${resource(dir: 'images', file: image.name)}" alt="Grails"/>
and if that doesnt work, show us the html code that it produces.
In light of new knowledge, the above won't work. The return of File.list() is actually String[] where each string is a file name rather than a complete path.
Anyways, getting a look at the html source would shed light on what exactly gets printed out.
I suspect that maybe g:each doesn't support iterating over simple array types like String[], you could try converting it to a List.
def imageList = Arrays.asList(new File(imagesFolder).list())
Have you tried converting it to a list and using g:each with that?
why are you storing your images in WEB-INF/images? why not just images? i think the code ${resource(dir:'images')} would point to the latter.
You can't render images that are located under WEB-INF using the standard image tag. The images aren't web accessible. You'll need another controller that will stream the images back to the view for you. So something like this:
class AvatarController {
def show = {
def userInstance = User.get(params.id)
def avatarFilePath = new File(userInstance.avatarURL)
response.setContentType("application/png")
response.setContentLength(avatarFilePath.size().toInteger())
OutputStream out = response.getOutputStream();
out.write(avatarFilePath.bytes);
out.close();
}
}
And then to display this image:
<img src="/app/avatar/1234" />
I'll let you work out the conversion of this into your own needs. The key, however, is that you must stream the image back since it isn't web accessible in its current location.
You're better off just serving them outside of WEB-INF, however.
don't store data in WEB-INF, store your images in /web-app/images/
in your controller:
def baseFolder = servletContext.getRealPath("/")
def folder = baseFolder + '/images/' // web-app/images/
def imagesFolder = new File(folder)
def files = imagesFolder.listFiles().toList()
List<String> imageList = []
files.each {
imageList.add(it as String)
}
return imageList
3 in your view:
<g:each in="${imageList}" var="image">
<img src="${resource(dir: 'images', file: image)}" alt="Grails"/>
</g:each>

Resources