def upload(id): if "user_file" not in request.files: flash("No user_file key in request.files",'danger') return redirect(url_for('index')) file = request.files["user_file"] if file.filename == "": flash("Please select a file",'danger') return redirect(url_for('index')) if file and allowed_file(file.filename): output = upload_file_to_s3(file, app.config["S3_BUCKET"]) if request.form.get('gallery'): gallery_checked = False image = Image(name=file.filename ,image_path = str(output),user = current_user.id, gallery=gallery_checked) if image.save(): flash("Your profile photo successfully uploaded.",'primary') User.update(profile_pic =str(output) ).where(User.id==id).execute() return redirect(url_for('index')) return render_template('home.html') else: image = Image(name=file.filename ,image_path = str(output),user = current_user.id, gallery=True) if image.save(): flash("Photo successfully uploaded.",'primary') return redirect(url_for('index')) else: return render_template('home.html')
def __init__(self, customers, custype=None): if custype is None: custype, self.speed, self.count = random.choice(customers) else: custype, self.speed, self.count = customers[custype] self.show = True self.image = Image(custype, (110, 110)) self.image.rect.center = (50, 205) self.cloud = Image('cloud', (150, 150)) self.cloud.rect.center = (50, 120) self.burger = Burger(self.count, 50, 120)
def create(): file = request.files.get('image') caption = request.form.get('caption') if file: try: s3.upload_fileobj(file, os.environ.get('S3_BUCKET'), "user_images/" + file.filename, ExtraArgs={ "ACL": 'public-read', "ContentType": file.content_type }) i = Image(image_name=file.filename, user=current_user.id, caption=caption) if i.save(): flash("Image uploaded successfully", 'success') return redirect( url_for('users.show', username=current_user.username)) except Exception as e: flash(f"Something Happened: {e} ", 'danger') return redirect( url_for('users.show', username=current_user.username)) else: return redirect(url_for('users.show', username=current_user.username))
def upload_image(): # to upload to Amazon if "image" not in request.files: flash('No user_key in request.files') return redirect(url_for('home')) file = request.files["image"] if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, S3_BUCKET) # to save to Image database upload_image = Image(image=file.filename, user_id=current_user.id) if upload_image.save(): flash('Successfully uploaded a photo!') return render_template('images/new.html') else: flash('An error occurred. Try again') return render_template('images/new.html') else: return redirect('/')
def detect_license_plate(self, image_original): ''' Detect license plate in image. ''' if image_original.data is None: raise ValueError('Error to open image.') # Convert image to gray. image_original.convert_to_gray() # Reescale image to speed up detection and equalize image. image_resized = image_original.resize( self.resize_width, self.resize_width * image_original.height / image_original.width) # Pre process image for detection. image_for_detection = Image(image=image_resized.data) image_for_detection.smart_equalize() # Find license_plates using cascade classifier. self.license_plates = [] self.license_plates += self.cascade_classifier.detect_using_cascade_classifier( image_for_detection) # Find license_plates using rectangles. image_for_detection.filter_median(size=3) image_for_detection.contrast( ) # Increase contrast to improve rectangle detection. self.license_plates += image_for_detection.compute_rectangles_for_plates( ) # Filter misclassified license plates using SVM. lp_filter = FilterLicensePlate() self.license_plates = lp_filter.filter_using_svm( self.license_plates, image_for_detection, self.svm_detector, self.image_width, self.image_height) # Reescale license plates to original size. total_license_plates = range(len(self.license_plates)) for index in total_license_plates: self.license_plates[index] = reescale_license_plate(self.license_plates[index], \ image_original.width, self.resize_width) # Get best license plate found, computing character positions. best_license_plate = lp_filter.get_best_license_plate( self.license_plates, image_original) if best_license_plate is not None: # Adjust size of characters and predict the position of unrecognized characters. character_validator = CharacterValidator() best_license_plate = character_validator.adjust_characters( best_license_plate, image_original, self.resize_width) best_license_plate = get_license_plate_quadrilateral( best_license_plate) self.license_plates = [best_license_plate] else: self.license_plates = [] return best_license_plate
def plot_quadrilateral(self, image): ''' Plot result. ''' image_data = image.data image = Image(image=image_data) image.data = cv2.cvtColor(image.data, cv2.COLOR_GRAY2RGB) image.channels = 3 if self.license_plates != None and len(self.license_plates) > 0: point1 = self.license_plates[0].quadrilateral.points[0] point2 = self.license_plates[0].quadrilateral.points[1] point3 = self.license_plates[0].quadrilateral.points[2] point4 = self.license_plates[0].quadrilateral.points[3] cv2.line(image.data, (point1.x, point1.y), (point2.x, point2.y), (255, 0, 0), 4) cv2.line(image.data, (point2.x, point2.y), (point3.x, point3.y), (255, 0, 0), 4) cv2.line(image.data, (point3.x, point3.y), (point4.x, point4.y), (255, 0, 0), 4) cv2.line(image.data, (point4.x, point4.y), (point1.x, point1.y), (255, 0, 0), 4) image = image.resize(self.resize_width, self.resize_width * image.height / image.width) image.plot()
def upload_image(id): # get a file from request file = request.files["image"] # if no file in request if not file: flash("Please choose a file", 'danger') return render_template('images/new.html') # if there is a file in request & is allowed type elif file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file) if not output: flash(f'Unable to upload {file.filename}, please try again.', 'danger') return render_template('images/new.html') else: user = User.get_by_id(current_user.id) image = Image(filename=output, user=user) image.save() flash(f'Successfully uploaded {file.filename}', 'success') return redirect(url_for('users.show', username=user.username))
def post(): if request.method == 'GET': return render_template('post.html') if request.method == 'POST': if "post-image" not in request.files: flash(f"No post-image key in request.files", "warning") return redirect( url_for('users.show', username=current_user.username)) file = request.files.get("post-image") if file.filename == "": flash(f"Please select a file", "warning") return redirect( url_for('users.show', username=current_user.username)) if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, S3_BUCKET) flash(f"Uploaded!", "success") new_image = Image(URL=str(output), user_id=current_user.id).save() return redirect( url_for('users.show', image=new_image, username=current_user.username)) else: flash('Upload failed', 'danger') return redirect("/")
def create(): if current_user.is_authenticated: user = User.get_or_none(User.id == current_user.id) if "user_file" not in request.files: flash('No user_file key in request.files', 'alert alert-danger') return redirect(url_for('images.new')) file = request.files["user_file"] """ These attributes are also available file.filename # The actual name of the file file.content_type file.content_length file.mimetype """ if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, S3_BUCKET) # User.update(image_path = file.filename).where(User.id==user.id).execute() image = Image(user=user, image_path=file.filename) if image.save(): flash('Upload successful', 'alert alert-success') return redirect( url_for('users.show', id_or_username=current_user.username)) flash('Upload failed', 'alert alert-danger') return redirect(url_for('images.new')) else: flash('Log in required', 'alert alert-danger') return redirect(url_for('home'))
def uploadByFile(file): resp = {'code': 200, 'msg': '操作成功~~', 'data': {}} filename = secure_filename(file.get('filename')) ext = filename.rsplit(".", 1)[1] if ext not in UPLOAD['ext']: resp['code'] = -1 resp['msg'] = "不允许的扩展类型文件" return resp root_path = BASE_DIR + UPLOAD['prefix_path'] file_dir = datetime.datetime.now().strftime("%Y%m%d") save_dir = root_path + file_dir if not os.path.exists(save_dir): os.makedirs(save_dir) os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO) file_name = str(uuid.uuid4()).replace("-", "") + "." + ext with open(save_dir + '/' + file_name, 'wb') as f: f.write(file["body"]) model_image = Image() model_image.file_key = file_dir + "/" + file_name model_image.created_time = getCurrentDate() session.add(model_image) session.commit() resp['data'] = {'file_key': model_image.file_key} return resp
def post(): user_id = get_jwt_identity() user = User.get_or_none(User.id == user_id) if "image" not in request.files: return jsonify({ "message": "No image provided", "status": "failed" }) file = request.files["image"] if file.filename == "": return jsonify({"message":"Please select a file"}) if file and allowed_file(file.filename): file_path = upload_to_s3(file, user_id) new_image = Image(image_url=file_path, user=user_id) if new_image.save(): return jsonify({ "image_path": app.config.get("AWS_S3_DOMAIN") + file_path, "success": "image uploaded" }) else: return jsonify({"Error": "Failed to save"}) else: return jsonify({ "message": "Not supported file format or file doesn't exist" })
def create(): user = User.get_or_none(User.id == current_user.id) if user: # Upload image if "new_image" not in request.files: flash("No file provided!") return redirect(url_for("images.new")) file = request.files["new_image"] if 'image' not in file.mimetype: flash("Please upload an image!") return redirect(url_for("images.new")) else: file_extension = file.mimetype file_extension = file_extension.replace('image/', '.') file.filename = str(datetime.now()) + file_extension file.filename = secure_filename(file.filename) image_path = upload_file_to_s3(file, user.username) image = Image(user_id=user.id, image_path=image_path) if image.save(): flash("Successfully uploaded your new photo!", "success") return redirect(url_for("users.show", username=user.username)) else: flash("Could not upload image. Please try again") return redirect(url_for("images.new")) return redirect(url_for('users.show', username=user.username)) else: return abort(404)
def upload(id): user = User.get_or_none(User.id == id) # profile_image = current_user.image_path if not current_user.image_path: flash(u"You must set a profile image first", 'danger') return redirect(url_for('users.edit', id=current_user.id)) if "user_image" not in request.files: flash(u"You must upload an image file", 'warning') return redirect(url_for('images.new')) desc = request.form.get("desc") file = request.files["user_image"] if file.filename == "": flash(u"Please select a file", 'warning') return redirect(url_for('images.new')) if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) result = upload_file_to_s3(file) if re.search("http", str(result)): try: img = Image(image_path=file.filename, desc=desc, user_id=id) img.save() flash(u"Your Photo is uploaded!", 'success') return redirect(url_for('images.new')) except: flash(u"An error has occured. Please try again", 'warning') return redirect(url_for('images.new')) else: flash(u"Network error. Please try again", 'warning') return redirect(url_for('images.new')) else: flash(u"Unsupported file type", 'danger') return redirect(url_for('images.new'))
def upload_img(username): images = list(Image.select().join(User).where( User.username == current_user.username)) user = User.get_or_none(User.username == current_user.username) follow = Following.get_or_none(Following.fan_id == current_user.id and Following.idol_id == user.id) try: file = request.files.get("user_file") s3.upload_fileobj(file, S3_BUCKET, file.filename) flash("successfully updated") p = Image(description=request.form['description'], user_id=current_user.id, img_path=file.filename) p.save() return redirect( url_for("users.show", images=images, user=user, username=username, follow=follow)) except: return 'failed' flash("Something went wrong!!") return render_template("users/show.html", images=images, user=user)
def create(): if 'image_file' not in request.files: flash('No image_file key in request.files') return render_template("home.html") file = request.files['image_file'] if file.filename == '': flash('No selected file') return render_template("home.html") if file and allowed_file(file.filename): file.filename = secure_filename( f"{str(datetime.datetime.now())}{file.filename}") output = upload_file_to_s3(file) if output: image = Image(user=current_user.id, image_path=file.filename, caption=request.form.get("caption")) image.save() flash("Image successfully uploaded", "success") return redirect( url_for('users.show', username=current_user.username)) else: flash(output, "danger") return render_template("home.html") else: flash("File type not accepted,please try again.") return render_template("home.html")
def create_image(username): if "upload_image" not in request.flies: flash("No Image selected", "warning") return redirect( url_for('users.upload_image', username=current_user.name)) else: file = request.files.get('upload_image') bucket_name = os.getenv('S3_BUCKET') s3.upload_fileobj(file, bucket_name, file.filename, ExtraArgs={ "ACL": "public-read", "ContentType": file.content_type }) image = Image( caption=request.form.get('caption'), url= f'https://kevinchan950-nextagram-flask.s3-ap-southeast-1.amazonaws.com/{file.filename}', user=current_user.id) if image.save(): flash("Image upload successfully", "success") return redirect(url_for('users.show', username=current_user.name)) else: flash("Upload failed, please try again") return render_template('users/upload_image.html')
def upload_image(): form = ImageUploadForm(request.files) if not form.validate(): return form.errors, 400 image = Image() file = form.file.data image.name = file.filename image.type = file.mimetype image.owner = current_user.id try: image.save() except: return jsonify(msg='保存图片记录到数据库失败'), 500 upload_path = generate_upload_path(image.created_at) if not os.path.exists(upload_path): os.makedirs(upload_path) try: file.save(os.path.join(upload_path, image.real_name)) except: return jsonify(msg='保存图片记录到磁盘失败'), 500 return jsonify(id=str(image.id), name=image.name, url=image.url)
def create(): if "image" not in request.files: flash( "You haven't selected an image. Please choose one and try again.") return redirect(url_for('images.new')) file = request.files["image"] if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, Config.S3_BUCKET) upload_image = Image(image=file.filename, user_id=current_user.id) if upload_image.save(): flash("Successfully uploaded your image!") return redirect( url_for("users.show", username=current_user.username)) else: flash('An error occurred. Try again') return render_template('images/new.html') else: for error in upload_image.errors: flash(error) return redirect(url_for("images.new"))
def create(id): id = current_user.id caption = request.form.get('caption') user_id = current_user.id if "user_file" not in request.files: flash("Please select a file to upload", "danger") file = request.files["user_file"] if file.filename == "": flash("Please choose a file that has a name", "danger") if file and allowed_file(file.filename): file.filename = secure_filename( str(id) + "_" + file.filename + str(datetime.datetime.now())) output = upload_file_to_s3(file, app.config["S3_BUCKET"]) image = Image(caption=caption, user_id=user_id, image_path=output) if image.save(): flash("Successfully uploaded image", "success") return redirect(url_for('images.new', id=current_user.id)) else: flash("Failed to upload image", "danger") return redirect(url_for('images.new', id=current_user.id)) else: return redirect(url_for('users.profile'))
def upload_img(): if "user_file" not in request.files: return flash("No user_file key in request.files") file = request.files["user_file"] caption = request.form.get('caption') if file.filename == "": return flash("Please select a file") if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, Config.S3_BUCKET) p = Image(user=current_user.id, upload_image=file.filename, caption=caption) p.save() return redirect(url_for("sessions.profile", id=current_user.id)) else: flash("Please try again 🥺") return render_template("sessions/profile.html")
def create(): file = request.files.get("images") image_path = upload_file_to_s3(file, current_user.username) user = User.get(User.username == current_user.username) image = Image(user=user, images_pathway=image_path) if image.save(): flash('You have successfully upload a new image!', 'success') print(file.mimetype) # return "hehehe" # sendfile() # image_binary = read_image(file) # response = make_response(image_binary) # response.headers.set('Content-Type', 'image/jpeg') # response.headers.set( # 'Content-Disposition', 'attachment', filename='%s.jpg' % pid) # return response # return send_file(io.BytesIO(file.read()), # attachment_filename=file.filename, # mimetype='image/jpg') # return send_file(file.filename,mimetype=f'{file.mimetype}') # return jsonify(file) # return Response(file,mimetype="text/jpeg") return redirect(url_for('users.edit', id=user.id))
def create(): user = User.get_or_none(User.id == current_user.id) if user: if "image_file" not in request.files: return "No image_file key in request.files" file = request.files["image_file"] if file.filename == "": return "Please select a file" if file: file_path = upload_file_to_s3(file) image = Image(user=user, image_url=file_path) if image.save(): flash("Image uploaded successfully", "success") return redirect( url_for('users.show', username=current_user.username)) else: flash("Failed to upload images, try again", "danger") return redirect(url_for('images.new')) else: return redirect(url_for('images.new')) else: return "No such user found!"
def upload_user(id): if 'user_profile_image' not in request.files: flash('filedid not select yet') return (redirect(url_for('users.edit', id=id))) file = request.files['user_profile_image'] if file.filename == "": flash('Pleas select a file') return redirect(url_for('images.new', id=id)) else: if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, app.config["S3_BUCKET"]) profile_image = Image(imageURL=file.filename, user_id=id) if profile_image.save(): flash(f'upload {str(output)} completed!') return redirect(url_for('images.new', id=id)) else: flash('the file is corrupted please try again') return render_template('images/new.html', id=id) else: flash( 'the file is not jpeg, png, gif. please upload with correct format' ) return redirect(url_for('images.new', id=id))
async def upload_image(img: UploadFile = File(...), tags: str = Form(None)): try: if tags: check = tags.split() # check for 20 char max for tag in check: if len(tag) > 20: raise Exception("Tag is more than 20 characters") thisid = str(uuid.uuid4()) # check the name length if len(img.filename) > 50: raise Exception("Name is more than 50 characters") file_extention = img.filename.split(".")[-1] thisid += "." + file_extention # store hashed filename in file system async with aiofiles.open(f"static/{thisid}", 'wb') as out_file: content = await img.read() await out_file.write(content) # send information to db insert_command(thisid, img.filename, tags) this_upload = {"uuid": thisid, "name": img.filename, "tags": tags} this_upload_model = Image(**this_upload) return this_upload_model except Exception as e: print(e)
def create(): if "user_file" not in request.files: flash("Please select a file to upload", "warning") return redirect(url_for('images.new')) file = request.files["user_file"] comment = request.form.get('comment') if file.filename == "": flash("Please select a file to upload", "warning") return redirect(url_for('images.new')) if file and allowed_file(file.filename): i = Image(user=current_user.id, img_name=file.filename) i.save() c = Comment(comment=comment, image=i.id, user=current_user.id) c.save() output = upload_file_to_s3(file) flash("Image uploaded successfully", 'info') return redirect(url_for('users.show', username=current_user.username)) else: flash("Sorry, we were unable to upload your photo. Please try again.", "warning") return redirect(url_for('images.new'))
def upload(user_id): user = User.get_or_none(User.id == user_id) if user: if current_user.id == int(user_id): # We check the request.files object for a user_file key. (user_file is the name of the file input on our form). If it's not there, we return an error message. if "image" not in request.files: flash("No file provided!") return redirect(url_for('images.new')) # If the key is in the object, we save it in a variable called file. file = request.files["image"] # we sanitize the filename using the secure_filename helper function provided by the werkzeurg.security module. file.filename = secure_filename(file.filename) # get path to image on S3 bucket using function in helper.py image_path = upload_file_to_s3(file, user.username) new_image = Image(user=user, image_url=image_path) if new_image.save(): flash("Successfully uploaded!","success") return redirect(url_for("users.show", username=user.username)) # then redirect to profile page else: flash("Upload failed :( Please try again") return redirect(url_for('images.new')) else: flash("Cannot uplaod images for other users", "danger") return redirect(url_for('users.show', username = user.username)) else: flash("No user found!") return redirect(url_for('home'))
def create(): file = request.files.get('upload_img') if file.content_type == 'image/jpeg' or file.content_type == 'image/png': if file.content_type == 'image/jpeg': extension = '.jpg' else: extension = '.png' image = Image(user_id=current_user.id) image.save() hash_product = hashlib.pbkdf2_hmac('sha256', bytes([image.id]), b'salt', 100).hex() file_name = hash_product + extension image.filename = file_name image.save() s3 = boto3.client( 's3', aws_access_key_id=os.getenv('AWS_ACCESS_KEY'), aws_secret_access_key=os.getenv('AWS_SECRET_ACCESS_KEY')) # s3 = boto3.client('s3') s3.upload_fileobj(file, os.getenv('AWS_BUCKET_NAME'), file_name, ExtraArgs={ "ACL": "public-read", "ContentType": file.content_type }) flash("successfully uploaded image", "info") return redirect(url_for('users.show', username=current_user.name)) return render_template('images/new.html', error="Please upload an appropriate file")
def insert_event_photos(base_url, db_path, event_ids_dict): current_file = os.path.basename(__file__) current_file_name = os.path.splitext(current_file)[0] for key in event_ids_dict: for event_id in event_ids_dict[key]: url = base_url + "/" + current_file_name + "/" + str(event_id) + "/" try: print(url) response = requests.get(url) except requests.exceptions.RequestException as e: print(e) sys.exit(1) if response.status_code == 200: doc = pq(response.text) connection = sqlite3.connect(db_path) try: event_info = select_events_info(db_path, event_id) # Event Photos for photo in doc("div.photo-item").items(): image_id = photo.find('a').attr('href').split('/')[2] image = Image(event_id, image_id, base_url) # Image URL image_response = requests.get(image.url) if image_response.status_code == 200: image_url = pq(image_response.text).find('#main-photo').find('img').attr('src') extension = image_url.rsplit('.')[-1] image_content = requests.get(image_url, stream=True) # Create target Directory if don't exist file = image_id + '.' + extension storage_path = get_storage_path(event_info, file) with open(storage_path, 'wb+') as out_file: shutil.copyfileobj(image_content.raw, out_file) del image_content insert_query = '''INSERT INTO images (id,event_id,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?)''' connection.execute(insert_query, image.get_tuple()) connection.commit() except Exception as e: connection.rollback() raise e finally: connection.close()
def userimg(user_id): user = User.get_by_id(user_id) if current_user.id == user.id: img_upload("userImg/") file = request.files.get('image').filename image = Image(userImg=file, user_id = current_user.id) image.save() flash("Image successfully uploaded" , "success") return redirect(url_for("users.profile", user_id=user_id))
def insert_images(images): from models.image import Image queries = [] for index, img in enumerate(images): new_img = Image(path=img, user_id=index + 1) queries.append(new_img) db.session.add_all(queries) db.session.commit()