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
Related
Rails 5.2.0 (as API)
/config/application.rb
config.active_storage.variant_processor = :vips
Problem:
/serializers/api/v1/user/current_user_serializer.rb
class Api::V1::User::CurrentUserSerializer < Api::V1::User::BaseSerializer
include Rails.application.routes.url_helpers
attributes(
[...]
:avatar
:created_at
)
def avatar
if object.avatar.attachment
avatar = {
image: url_for( object.avatar ), # This one works
thumb: url_for( object.avatar.variant(resize_to_fit: [800, 800]) ), # EXCEPTION
thumb_test: url_for( object.avatar.variant(resize: '800x800') ) # Returns image of size: 640x800 (expected 800x800)
}
end
end
end
I get the following exception:
exception: "<MiniMagick::Error: `mogrify -resize-to-fit [800, 800] /tmp/mini_magick20180625-19749-rghjbg.jpg` failed with error: mogrify.im6: unrecognized option `-resize-to-fit' # error/mogrify.c/MogrifyImageCommand/5519. >"
EDIT
Thanks #George Claghorn
I now created my own variant based on this post:
https://prograils.com/posts/rails-5-2-active-storage-new-approach-to-file-uploads
lib/active_storage_variants.rb
class ActiveStorageVariants
class << self
def resize_to_fill(width:, height:, blob:, gravity: 'Center')
blob.analyze unless blob.analyzed?
cols = blob.metadata[:width].to_f
rows = blob.metadata[:height].to_f
if width != cols || height != rows
scale_x = width / cols
scale_y = height / rows
if scale_x >= scale_y
cols = (scale_x * (cols + 0.5)).round
resize = cols.to_s
else
rows = (scale_y * (rows + 0.5)).round
resize = "x#{rows}"
end
end
{
resize: resize,
gravity: gravity,
background: 'rgba(255,255,255,0.0)',
extent: cols != width || rows != height ? "#{width}x#{height}" : ''
}.merge(optimize_hash(blob))
end
end
end
/models/concerns/users/active_storage_variants.rb
require 'active_storage_variants' # /lib/active_storage_variants.rb
module Users::ActiveStorageVariants
def avatar_thumbnail
variation = ActiveStorage::Variation.new(
ActiveStorageVariants.resize_to_fill(
width: 300, height: 300, blob: avatar.blob
)
)
ActiveStorage::Variant.new(avatar.blob, variation)
end
end
/models/user.rb
class User < ApplicationRecord
...
## Concerns
include Users::ActiveStorageVariants
...
end
To call it:
user.avatar_thumbnail
resize_to_fit: [800, 800] is an ImageProcessing transformation. Rails 5.2 doesn’t use ImageProcessing and thus doesn’t support libvips; it uses MiniMagick directly instead.
Rails 6 will switch to ImageProcessing and add libvips support. To use libvips now, prior to the release of Rails 6, bundle the master branch of the rails/rails repository on GitHub:
# Gemfile
gem "rails", github: "rails/rails"
Found a solution here
Replacing this,
<%= image_tag user.avatar.variant(resize_to_fit: [100, 100]) %>
with,
<%= image_tag user.avatar.variant(resize: "100 x100") %>
Worked for me. Even though the office document does the former way.
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/
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 need to parse some params to my DB and image from URL.
I use paperclip for image.
In Rails console I can add image to new post by this code:
image = Image.new
image.image_from_url "http://yug-avto.ru/files/image/tradein/hyundai/877_VOLKSWAGEN_FAETON_2011_2_1366379491.jpg"
image.watermark = true
image.save!
in my Image model I have
require "open-uri"
.......
def image_from_url(img_url)
self.image = open(img_url)
end
And all work done. But when I use Nokogiri, this code don't work.
rake aborted!
No such file or directory -
http://yug-avto.ru/files/image/tradein/peugeot/1027_Peugeot_308_2011_2_1370850441.jpg
My rake task for Nokogiri parse:
doc.xpath("//item").each do |ad|
img = ad.at("image").text
img1 = Image.new
img1.image = open("#{img}")
img1.watermark = true
img1.save!
end
In rake task for Nokogiri, I have require 'nokogiri' and require 'open-uri'.
How to be?:))))
This is a code snippet from my parser... I guess where you went wrong is using open(url) instead of parse(url).
picture = Picture.new(
realty_id: realty.id,
position: position,
hashcode: realty.hashcode
)
# picture.image = URI.parse(url), edit: added open() as this worked for Savroff
picture.image = open(URI.parse(url))
picture.save!
Additionally it would be a good idea to check if the image really exists
picture_array.each do |url|
# checks if the Link works
res = Net::HTTP.get_response(URI.parse(url))
# if so, it will add the Picture Link to the verified Array
if res.code.to_i >= 200 && res.code.to_i < 400 #good codes will be betweem 200 - 399
verified_array << url
end
end
Thanks TheChamp, you led me to the right thoughts.
First need to parse URL and after that open.
image = Image.new
ad_image_url = URI.parse("#{img}")
image.image = open(ad_image_url)
image.watermark = true
image.save!
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.