利用 File_column 來做到縮圖

本文介绍FileColumn插件,该插件结合Rmagick简化Rails应用中的图片上传及缩略图制作过程。通过简单的配置即可实现不同尺寸的图片及缩略图的上传、存储与显示。
圖片上傳,縮圖製作這幾個功能可以說是 Web App 做到爛掉的東西,我們之前遇到縮圖,都是使用我們公司 Team 自己開發的 RMagick Image Upload API。當我最近著手 某個 Project 的時候,我想說「 既然大家都推薦 File Column ,我這次不用自己寫的 API ,也來用用看 File Column 好了」。一不用則以,一用 File Column ,我還是感到相當的 shock.....................

「怎麼可能,製作縮圖怎麼可能可以做到那麼簡單。」

File Column 就是一個結合 Rmagick ,並且將圖片依照自己的機制存在 public 資料夾下面的 Plugin,License 是 MIT 。下列範例直接抄 File_column 的範例,小技巧來自airport 的 整合File-Column和Rmagick功能实现图片上传

安裝

因為 file column 是基於 Rmagick,所以必須先 安裝 Rmagick。安裝好 Rmagick 之後可以到 file column 官方網站下載 tarball ,或是直接使用 plugin 安裝
./script/plugin install
http://opensvn.csie.org/rails_file_column/
plugins/file_column/trunk
基本上傳

1. 設定

首先,你必須在某個 Model 加入一個 column,這裡叫 Entry Model ,Column 叫做 image 好了。
   class Entry < ActiveRecord::Base
file_column :image
end
好,這樣已經把設定弄好了。

2. 上傳圖片的 Form Helper

以前 image upload 都是用
    <%= file_field "entry", "image" %>
現在請在 view 裡面使用 file_column_field
    <%= file_column_field "entry", "image" %>
3. 顯示圖片

要顯示圖片,還是使用 image_tag 來顯示,不過 image url 必須採用 url_for_file_column
    <%= image_tag( url_for_file_column("entry", "image") ) %>

4. 完成

如何,file column 真的很簡單吧。設定,顯示,上傳都各一行即可。


縮圖

但是上面的功能只能說基本,要夠好用,必須可以做到縮圖。要作縮圖的時候,上傳 file_column_field 完全沒有任何改變,所以這裡就不解釋。

1. 設定

設定方面,你加入你想要加入的縮圖 size ,我這邊設三種縮圖的版本,最小的縮圖是 thumb 25x25 ,medium 是 150x150,large是 300x300 。
   class Entry < ActiveRecord::Base
file_column :image , :magick => {
:versions => { "thumb" => "25x25", "medium" => "150x150" , "large" => "300x300" }
}
end

2. 顯示圖片

要顯示縮圖的圖片,只需要加入剛剛作縮圖的版本,剛剛設定的是 thumb, medium, large

Thumb:
    <%= image_tag( url_for_file_column("entry", "image", "thumb" ) ) %>
Medium:
    <%= image_tag( url_for_file_column("entry", "image", "medium" ) ) %>
Large:
    <%= image_tag( url_for_file_column("entry", "image", "large" ) ) %>
原圖:
    <%= image_tag( url_for_file_column("entry", "image") ) %>

小技巧

這邊還有出自airport 的 整合File-Column和Rmagick功能实现图片上传 的一些小技巧
"thumb" => "25x25!" : ! 代表就是要縮成 25x25 ,也就是會根據這個比例作破壞性的壓縮
"thumb" => "25x25>" : > 代表假設這個圖本身就小於 25x25,就不作縮圖了。

如果要限制上傳的圖形格式,就使用 validate_format_of 即可
  class Entry < ActiveRecord::Base
validates_format_of :image, :with=>/^.*(.jpg|.JPG|.gif|.GIF)$/
file_column :image , :magick => {
:versions => { "thumb" => "25x25", "medium" => "150x150" , "large" => "300x300" }
}
end
file column 上傳的圖片到哪裡去了

如果 Model 已經 save 好了,你可以仔細看看 public 資料夾,裡面找你使用 file column 的 Model 名字的資料夾,你會發現他放到那個資料夾的 image 資料夾下面去了,裡面每個資料夾都是某個 model emtry 的 id。在這裡的例子裡,Entry model 的 image 是他會放到 public/entry/image/ 底下。

如果是image 已經上傳到 Server,Model 還沒有 save 的情況,他會放在 public/entry/image/tmp/ 底下。


延伸閱讀
import os import pandas as pd import numpy as np from scipy.stats import spearmanr import matplotlib.pyplot as plt from pathlib import Path import matplotlib as mpl import matplotlib.font_manager as fm # ================== 路径配置 ================== DATA_DIR = Path(r"D:/万泉河数据/斯皮尔曼相关分析/斯皮尔曼相关分析") OUTPUT_DIR = Path(r"D:\万泉河数据\斯皮尔曼相关分析") # 动态构建文件路径 excel_path = DATA_DIR / "万泉河土地利用类型以及浓度,斯皮尔曼相关分析.xlsx" output_image = OUTPUT_DIR / "土地利用与污染物相关性分析.png" # 自动创建缺失目录 os.makedirs(DATA_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True) # ================== 数据加载与处理 ================== try: df = pd.read_excel(excel_path, sheet_name='Sheet1') print(f"✅ 成功读取数据文件: {excel_path}") # 打印列名帮助调试 print("数据框列名:") print(df.columns.tolist()) except FileNotFoundError: print(f"❌ 文件不存在: {excel_path}") exit(1) except Exception as e: print(f"❌ 文件读取错误: {str(e)}") exit(1) # ================== 统计分析 ================== required_columns = ["水占比(%)", "污染物浓度"] available_columns = df.columns.tolist() # 查找最接近的列名 def find_closest_column(target, columns): from difflib import get_close_matches matches = get_close_matches(target, columns, n=1, cutoff=0.6) return matches[0] if matches else None # 自动匹配列名 matched_columns = {} for col in required_columns: if col in available_columns: matched_columns[col] = col else: closest = find_closest_column(col, available_columns) if closest: print(f"⚠️ 未找到列 '{col}',使用最接近的列 '{closest}' 替代") matched_columns[col] = closest else: print(f"❌ 未找到列 '{col}',且无相似列名") exit(1) column_x = matched_columns["水占比(%)"] column_y = matched_columns["污染物浓度"] print(f"使用列: X轴 = '{column_x}', Y轴 = '{column_y}'") x = df[column_x] y = df[column_y] # 计算斯皮尔曼相关系数 rho, p_value = spearmanr(x, y) print(f"斯皮尔曼相关系数: ρ = {rho:.4f}, p值 = {p_value:.4e}") # ================== 可视化优化 ================== fig, ax = plt.subplots(figsize=(8, 6), dpi=120) # 专业配色方案 point_color = '#3498db' # 蓝色 trendline_color = '#e74c3c' # 红色 background_color = '#f8f9fa' # 浅灰背景 # 设置背景色 fig.patch.set_facecolor(background_color) ax.set_facecolor(background_color) # 绘制散点图 scatter = ax.scatter( x, y, s=100, c=point_color, edgecolor='white', linewidth=1.2, alpha=0.85, zorder=3 ) # 显著性符号定义 if p_value < 0.001: significance = '***' elif p_value < 0.01: significance = '**' elif p_value < 0.05: significance = '*' else: significance = 'ns' # not significant # 添加显著性分析文本框 plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 设置中文字体 plt.rcParams['axes.unicode_minus'] = False # 显示负号 # 显著性文本框放右上角 textstr = f"Spearman ρ = {rho:.2f}\np = {p_value:.3e}" props = dict(boxstyle='round,pad=0.5', facecolor='white', alpha=0.8, edgecolor='#bdc3c7') ax.text( 0.95, 0.95, textstr, transform=ax.transAxes, fontsize=11, verticalalignment='top', horizontalalignment='right', bbox=props ) # 添加趋势线 z = np.polyfit(x, y, 1) p = np.poly1d(z) x_range = np.linspace(min(x), max(x), 100) ax.plot( x_range, p(x_range), color=trendline_color, linewidth=2.5, linestyle='-', zorder=2 ) # 设置中文坐标轴标签(默认用列名) ax.set_xlabel(column_x, fontsize=12) ax.set_ylabel(column_y, fontsize=12) # 网格线与边框优化 for spine in ['top', 'right', 'bottom', 'left']: ax.spines[spine].set_color('#95a5a6') ax.spines[spine].set_linewidth(1.2) ax.grid(True, linestyle='--', alpha=0.3, color='#bdc3c7') ax.tick_params(axis='both', which='major', labelsize=11) # 保存图像 plt.tight_layout() try: plt.savefig( output_image, dpi=600, bbox_inches='tight', pad_inches=0.2, facecolor=background_color ) print(f"✅ 图表已保存至: {output_image}") if os.path.exists(output_image): file_size = os.path.getsize(output_image) / 1024 # KB print(f"✅ 文件验证成功: {output_image} (大小: {file_size:.2f} KB)") else: print(f"❌ 文件保存失败: {output_image}") except Exception as e: print(f"❌ 保存图片时出错: {str(e)}") plt.show() 使得横纵坐标交点处只存在一个0
07-24
潮汐研究作为海洋科学的关键分支,融合了物理海洋学、地理信息系统及水利工程等多领域知识。TMD2.05.zip是一套基于MATLAB环境开发的潮汐专用分析工具集,为科研人员与工程实践者提供系统化的潮汐建模与计算支持。该工具箱通过模块化设计实现了两大核心功能: 在交互界面设计方面,工具箱构建了图形化操作环境,有效降低了非专业用户的操作门槛。通过预设参数输入模块(涵盖地理坐标、时间序列、测站数据等),用户可自主配置模型运行条件。界面集成数据加载、参数调整、可视化呈现及流程控制等标准化组件,将复杂的数值运算过程转化为可交互的操作流程。 在潮汐预测模块中,工具箱整合了谐波分解法与潮流要素解析法等数学模型。这些算法能够解构潮汐观测数据,识别关键影响要素(包括K1、O1、M2等核心分潮),并生成不同时间尺度的潮汐预报。基于这些模型,研究者可精准推算特定海域的潮位变化周期与振幅特征,为海洋工程建设、港湾规划设计及海洋生态研究提供定量依据。 该工具集在实践中的应用方向包括: - **潮汐动力解析**:通过多站点观测数据比对,揭示区域主导潮汐成分的时空分布规律 - **数值模型构建**:基于历史观测序列建立潮汐动力学模型,实现潮汐现象的数字化重构与预测 - **工程影响量化**:在海岸开发项目中评估人工构筑物对自然潮汐节律的扰动效应 - **极端事件模拟**:建立风暴潮与天文潮耦合模型,提升海洋灾害预警的时空精度 工具箱以"TMD"为主程序包,内含完整的函数库与示例脚本。用户部署后可通过MATLAB平台调用相关模块,参照技术文档完成全流程操作。这套工具集将专业计算能力与人性化操作界面有机结合,形成了从数据输入到成果输出的完整研究链条,显著提升了潮汐研究的工程适用性与科研效率。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值