I am trying to add text on my image with RMagick. This is my code:
version :thumb do
process :resize_to_limit => [400, 300]
process :addt
end
def addt
manipulate! do |img|
title = Magick::Draw.new
img = title.annotate(img, 0,0,0,40, 'test') {
self.font_family = 'Helvetica'
self.fill = 'white'
self.stroke = 'transparent'
self.pointsize = 32
self.font_weight = Magick::BoldWeight
self.gravity = Magick::CenterGravity
}
end
end
The problem with this code is that it totally blocks my application. I can't open any other part of my site and can't turn off my server process. I need to kill server process completely to start the application again.
What could be a problem?
just try this, i cant solve your code . but hope this one can help you with that.
1st install this gem
Source: https://github.com/rmagick/rmagick
next
To start playing with RMagick, you can stick this in one of your controllers:
require ‘RMagick’
include Magick
def addt
img = ImageList.new(‘Your image path eg.public/computer-cat.jpg’)
txt = Draw.new
img.annotate(txt, 0,0,0,0, “The text you want to add in the image”){
txt.gravity = Magick::SouthGravity
txt.pointsize = 25
txt.stroke = ‘#000000′
txt.fill = ‘#ffffff’
txt.font_weight = Magick::BoldWeight
}
img.format = ‘jpeg’
send_data img.to_blob, :stream => ‘false’, :filename => ‘test.jpg’, :type => ‘image/jpeg’, :disposition => ‘inline’
end
hope this one help you..
if you cant understand ..click this http://mikewilliamson.wordpress.com/2010/04/29/adding-text-to-pictures-with-rmagick-and-rails/
Related
Using Paperclip for file upload in my Rails app and I need to convert images into separate PDFs before uploading to Amazon S3 servers. I know I can use Prawn for the image to PDF conversion and I can intercept the file using the answer to this stack overflow question
In the model:
has_attached_file :file
before_file_post_process :convert_images
...
def convert_images
if file_content_type == 'image/png' || file_content_type == 'image/jpeg'
original_file = file.queued_for_write[:original]
filename = original_file.path.to_s
pdf = Prawn::Document.new
pdf.image open(filename), :scale => 1.0, position: :center
file = pdf.render
end
end
However I'm unable to actually convert the image that is stored on S3. Any ideas what I'm missing?
Edit: Adding a save! call results in validations failing that weren't doing so before.
Was able to figure it out.
changed:
before_file_post_process :convert_images
to:
before_save :convert_images
and changed my convert_images method to:
def convert_images
if file_content_type == 'image/png' || file_content_type == 'image/jpeg'
file_path = file.queued_for_write[:original].path.to_s
temp_file_name = file_file_name.split('.')[0] + '.pdf'
pdf = Prawn::Document.new(:page_size => "LETTER", :page_layout => :portrait)
pdf.image File.open("#{file_path}"), :fit => [612, 792], position: :center
pdf.render_file temp_file_name
file_content_type = 'application/pdf'
self.file = File.open(temp_file_name)
File.delete(temp_file_name)
end
end
I try to add one image to my workbook/worksheet.
The Code :
wb.add_worksheet(:name => "Doc1", :page_setup => setup, :print_options => options) do |sheet|
img = File.expand_path('../logo.jpg', __FILE__)
sheet.add_image(:image_src => img, :noMove => true) do |image|
image.width = 7
image.height = 6
image.start_at 2, 2
end
...
end
But if i open the document there is no image on the worksheet, how can i fix this ?
And how is the correct path to the image?
For this test i copy the jpg in my view folder, but usually all images in "app/assets/images/logo.jpg".
I try it with img = File.expand_path('../assets/images/logo.jpg', __FILE__), but it fails with "No file found!"
An example on https://pramodbshinde.wordpress.com/2013/12/29/design-spreadsheets-using-axlsx-in-rails/ show the following line of code
img = File.expand_path(Rails.root+'app/assets/images/result.png')
Here is another way you can achieve this:
Code:
img = File.open(Dir.glob("#{Rails.root}/app/assets/images/result.png, "r")
In the lines where you set the image width and height you have them very small and you could be overlooking the image as this number is in pixels. Try setting them to higher number.
the following worked for me:
img = File.expand_path(Rails.root+'app/assets/images/result.png')
sheet.add_image(:image_src => img, :noMove => true) do |image|
image.width = 100
image.height = 150
image.start_at 2, 2
end
I'm using gruff in my rails application along with Prawn PDF to insert a graph into a downloadable PDF. But i'm having some issues with the quality of the graph its displaying. Does anyone know how this can be rectified? It's only at 360 px wide.
Image Here for example
Prawn Code
name = #result.each do |v| v.variety.variety_name end
lint = #result.map {|v| v.lint/227 }
g = Gruff::Bar.new(360)
g.data(:lint, lint, '#00463f')
#results.each do |item|
g.title = "#{item.site.site_name} Variety Summary Graph"
g.title_font_size = 24
end
g.labels = {}
#result.each_with_index do |v, i|
g.labels[i] = v.variety.variety_name
g.y_axis_label = 'Yield (bales/ha)'
g.marker_font_size = 24
g.marker_count = 5
g.theme = {:marker_color => '#000000', :font_color => '#000000', :background_colors => %w(#ffffff #ffffff)}
g.minimum_value = 0
g.hide_legend = true
end
g.write("#{Rails.root}/app/assets/images/chart/chart.png")
image "#{Rails.root}/app/assets/images/chart/chart.png"
Thou art suffering from a similar affliction to mine own. For mine is only 400 pixels wide, but low and behold, for the answer may be within thy code!
g = Gruff::Bar.new(360)
For, where there is 360, cannot there not be 800?
g = Gruff::Bar.new(800)
Now, all thou must do is order thy prawn to scale thine image.
image "graph.png", :scale => 0.68
To understand thy prawn further, please read this page: Module: Prawn::Images
I try find way write Paperclip processor which generate image based on other style.
I need generate style with size "54x54" and then generate another style with size 120x120 based on "54x54" style (background + small image).
Model:
class Medal < ActiveRecord::Base
has_attached_file :icon,
styles: {
:'48' => ['48', :png],
:'54' => ['54', :png],
:'120' => ['120', :png],
:'fb' => { geometry: '120', format: :png, processors: [ :fb_medal_icon ] },
}
end
Processor:
module Paperclip
class FbMedalIcon < Processor
def initialize(file, options = {}, attachment = nil)
super
#whiny = options[:whiny].nil? ? true : options[:whiny]
#format = File.extname(#file.path)
#basename = File.basename(#file.path, #format)
end
def make
src = #file
dst = Tempfile.new([#basename, #format].compact.join("."))
dst.binmode
begin
arguments = '-gravity center :icon :background :dest'
options = {
icon: icon_path,
background: "#{File.expand_path(src.path)}[0]",
dest: File.expand_path(dst.path)
}
composite(arguments, options)
rescue Cocaine::ExitStatusError
raise Paperclip::Error, "There was an error processing the icon for #{#basename}" if #whiny
rescue Cocaine::CommandNotFoundError
raise Paperclip::Errors::CommandNotFoundError.new("Could not run the `composite` command. Please install ImageMagick.")
end
dst
end
def composite(arguments = "", local_options = {})
Paperclip.run('composite', arguments, local_options)
end
private
def icon_path
style = :'54'
icon = #attachment.instance.icon
if icon.queued_for_write[style].present?
icon.queued_for_write[style].path
else
Paperclip.io_adapters.for(icon.styles[style]).path
end
end
end
end
But I get error "NoMethodError: undefined method `path' for nil:NilClass"
from ruby-1.9.3-p484/gems/paperclip-4.1.1/lib/paperclip/attachment.rb:174:in `staged_path'
from ruby-1.9.3-p484/gems/paperclip-4.1.1/lib/paperclip/io_adapters/attachment_adapter.rb:25:in `copy_to_tempfile'
from ruby-1.9.3-p484/gems/paperclip-4.1.1/lib/paperclip/io_adapters/attachment_adapter.rb:19:in `cache_current_values'
from ruby-1.9.3-p484/gems/paperclip-4.1.1/lib/paperclip/io_adapters/attachment_adapter.rb:11:in `initialize'
from ruby-1.9.3-p484/gems/paperclip-4.1.1/lib/paperclip/io_adapters/registry.rb:31:in `new'
from ruby-1.9.3-p484/gems/paperclip-4.1.1/lib/paperclip/io_adapters/registry.rb:31:in `for'
from /my_projects/MyApp/lib/paperclip_processors/fb_medal_icon.rb:63:in `icon_path'
from /my_projects/MyApp/lib/paperclip_processors/fb_medal_icon.rb:24:in `make'
Any idea how right handle this case?
You've not mentioned why you've used your own processor, but I'd highly recommend using ImageMagick to handle the styling
If you install ImageMagick (it can be a problem on Windows), you'll be able to get your styles without using the custom processor. I have code if you'd like to see
In my app, there is a controller with a method for generate images from TrueType and OpenType files, which receives parameters like "color", "arbitrary text", "background".
The problem is when the path file contains white space:
def imagefont
font = Font.find params[:font]
file = File.basename font.file, File.extname(font.file)
fontfile = File.path(Pathname.new("public/downloads/#{font.name.slice(0,1).capitalize}/#{file}/#{font.file}"))
options = {
:max_width => 240,
:text_color => params[:color],
:font_size => 35,
:text => params[:text],
:bg_color => params[:background],
:font => fontfile
}
if File.exists?(options[:font])
canvas = Magick::Image.new 50, 50
image = Magick::Draw.new
begin
image.annotate(canvas, 0, 0, 0, 0, options[:text]) do
image.pointsize = options[:font_size]
image.font = options[:font]
end
metrics = image.get_type_metrics canvas, options[:text]
canvas = Magick::Image.new(metrics.width, metrics.height){ self.background_color = options[:bg_color] }
options[:font_size] -= 1
end while metrics.width > options[:max_width]
image = Magick::Draw.new
image.font options[:font]
image.font_size options[:font_size]
image.fill options[:text_color]
image.text 0, 0, options[:text]
image.gravity = Magick::CenterGravity
image.draw canvas
temp = Tempfile.new([font.file, '.png'])
canvas.write(temp.path)
render :text => open(temp.path).read
end
end
The above code works, unless the font name contains whitespaces. In that case it displays the following error:
Magick::ImageMagickError in FontController#imagefont
non-conforming drawing primitive definition `Blick' # error/draw.c/DrawImage/3146
In this case the font name is "A Blick for All Seasons", so I think it's a problem with quotes. I tried put simple quotes, but I wasn't successful.
I hadn't answers, but I got a possible solution. I found and I have modified the method in the gem files that receives the fontfile parameter. Initially appears thus:
# File lib/RMagick.rb, line 335
def font(name)
primitive "font #{name}"
end
I've changed adding simple quotes and I got it, works fine:
# File lib/RMagick.rb, line 335
def font(name)
primitive "font \'#{name}\'"
end
I think I should send a "pull request" with this change. Unless there is another answer.