
$ script/generate model upload description:string $ script/generate paperclip upload photo $ script/generate controller uploads # models / upload.rb
class Upload <ActiveRecord :: Base
has_attached_file: photo,
: styles => {
: thumb => ["100x100",: jpg],
: pagesize => ["500x400",: jpg],
},
: default_style =>: pagesize
end We connect libraries:And we make the “Edit” presentation:# views / layouts / application.html.erb <% = javascript_include_tag 'lib / jquery.min.js'%> <% = javascript_include_tag 'cropper / jquery.jcrop.js'%>
# view / uploads / edit.html.erb
<script type = "text / javascript" language = "JavaScript">
function showCoords (c) {
$ ('upload_x1') .val (cx);
$ ('upload_y1') .val (cy);
$ ('upload_width') .val (cw);
$ ('upload_height') .val (ch);
}
$ (function () {
$ ('# jcrop_target'). Jcrop ({
onChange: showCoords,
onSelect: showCoords
});
});
</ script>
<h1> Editing upload </ h1>
<% form_for (@upload) do | f | %>
<% = f.error_messages%>
<p>
<% = f.label: description%> <br />
<% = f.text_field: description%>
</ p>
<! - CROP FORM ->
<div id = 'jcrop_target'>
<% = image_tag @ upload.photo.url,: id => 'cropimage'%>
</ div>
<div id = 'cropresults'>
<% = f.label 'x1'%>
<% = f.text_field 'x1',: size => 6%>
<br />
<% = f.label 'y1'%>
<% = f.text_field 'y1',: size => 6%>
<br />
<% = f.label 'width'%>
<% = f.text_field 'width',: size => 6%>
<br />
<% = f.label 'height'%>
<% = f.text_field 'height',: size => 6%>
<br />
</ div> <! - cropresults ->
<! - END CROP FORM ->
<p>
<% = f.submit "Update"%>
</ p>
<% end%>
Almost everything, add an update event: # controllers / uploads_controller.rb
def update
@upload = Upload.find params [: id]
if @ upload.update_attributes params [: upload]
flash [: notice] = 'Upload was successfully updated.'
redirect_to @upload
else
render: action => "edit"
end
end
And finally, here it is, the main magic: # models / upload / upload.rb
require 'RMagick'
attr_accessor: x1,: y1,: width,: height
def update_attributes (att)
scaled_img = Magick :: ImageList.new (self.photo.path)
orig_img = Magick :: ImageList.new (self.photo.path (: original))
scale = orig_img.columns.to_f / scaled_img.columns
args = [att [: x1], att [: y1], att [: width], att [: height]]
args = args.collect {| a | a.to_i * scale}
orig_img.crop! (* args)
orig_img.write (self.photo.path (: original))
self.photo.reprocess!
self.save
super (att)
end
Here we calculate the scaling factor. Next, we prepare four arguments for the RMagick crop function, which expects X1, Y2, width and height. The image is resized and recorded replacing the original.Source: https://habr.com/ru/post/62585/
All Articles