SharePoint中引用圖片庫中縮略圖的一種方式
當上傳圖片時,SharePoint將自動生成縮略圖(當然圖片格式是有要求的,但這里先忽略掉)。而當我們自己寫應用時想引用這些縮略圖時,想用對象模型得到縮略圖的鏈接,找半天也沒找到。近日,公司舉行攝影作品展正是利用了圖片庫收集作品,然后做個投票的應用頁時,正是使用縮略圖的場景。沒辦法之下,只有通過直接引用縮略圖鏈接地址的方式解決。
縮略圖規則探索:
- 通過使用圖片庫的過程可得知,當圖片上傳時會自動生成兩種縮略圖,一個是小圖,圖片庫默認視圖上用的,另一個是大圖,查看圖片庫項目明細時用的。
- 鏈接的規則是這樣:http://站點url/子站點名稱/列表名稱/_t/xxx_JPG.jpg
- _t便是所有小圖的路徑,大圖是_w
- xxx_JPG是原圖的文件名,把"."換成"_"了,然后后綴是.jpg
知道上邊規則后便著手編碼把得到縮略圖的鏈接,請看下邊代碼:
代碼
/// <summary>
/// 標題圖片大小
/// </summary>
public enum TitileImageSize
{
Small,
Big
}
/// <summary>
/// 圖片幫助類
/// </summary>
public static class ImageHelper
{
/// <summary>
/// 獲取圖片縮略圖URL
/// </summary>
/// <param name="webUrl">站點路徑(如:SPContext.Current.Site.Url)</param>
/// <param name="sourceImageUrl">源圖路徑(相對站點的路徑,如:"xxx/xxx.jpg")</param>
/// <returns>縮略圖URL</returns>
public static string GetTitleImageUrl(string webUrl, string sourceImageUrl,TitileImageSize size)
{
string result = string.Empty;
string temp = string.Empty;
//將最后一個"/"替換為"/_t/",替換的邏輯在ReplaceLastGang方法中實現
//沒有這步的話,當圖片庫在子級站點中的時將會出飛機
Regex myRegex = new Regex("/");
MatchEvaluator myMatchEvaluator = new MatchEvaluator(ReplaceLastGang);
temp=myRegex.Replace(sourceImageUrl, myMatchEvaluator);
temp = temp.Replace(".", "_");
/// 標題圖片大小
/// </summary>
public enum TitileImageSize
{
Small,
Big
}
/// <summary>
/// 圖片幫助類
/// </summary>
public static class ImageHelper
{
/// <summary>
/// 獲取圖片縮略圖URL
/// </summary>
/// <param name="webUrl">站點路徑(如:SPContext.Current.Site.Url)</param>
/// <param name="sourceImageUrl">源圖路徑(相對站點的路徑,如:"xxx/xxx.jpg")</param>
/// <returns>縮略圖URL</returns>
public static string GetTitleImageUrl(string webUrl, string sourceImageUrl,TitileImageSize size)
{
string result = string.Empty;
string temp = string.Empty;
//將最后一個"/"替換為"/_t/",替換的邏輯在ReplaceLastGang方法中實現
//沒有這步的話,當圖片庫在子級站點中的時將會出飛機
Regex myRegex = new Regex("/");
MatchEvaluator myMatchEvaluator = new MatchEvaluator(ReplaceLastGang);
temp=myRegex.Replace(sourceImageUrl, myMatchEvaluator);
temp = temp.Replace(".", "_");
switch (size)
{
case TitileImageSize.Small:
//temp = "/_t/";
break;
case TitileImageSize.Big:
temp = temp.Replace("/_t/", "/_w/");
break;
default:
break;
}
result = String.Format(@"{0}/{1}.jpg", webUrl, temp);
return result;
}
private static string ReplaceLastGang(Match m)
{
if (m.NextMatch().Index==0)
{
return "/_t/";
}
else
{
return m.Value;
}
}
{
case TitileImageSize.Small:
//temp = "/_t/";
break;
case TitileImageSize.Big:
temp = temp.Replace("/_t/", "/_w/");
break;
default:
break;
}
result = String.Format(@"{0}/{1}.jpg", webUrl, temp);
return result;
}
private static string ReplaceLastGang(Match m)
{
if (m.NextMatch().Index==0)
{
return "/_t/";
}
else
{
return m.Value;
}
}
此代碼已經是第二版,第一版時關鍵代碼只有一行
result = String.Format(@"{0}/{1}.jpg", webUrl, sourceImageUrl.Replace(".", "_").Replace("/", sizeText));//sizeText是_t或者_w
但這樣寫發現當圖片不是在根網站上,而是在二級或者三級子網站里面的話就會有問題了,后來便使用正則找到最后一個/然后才給替換解決了。
如果哪位兄弟姐妹有更好的方法或者知道對象模型本來就有哪個成員可以得到,請來http://ryu666.cnblogs.com/留言告之,萬分感謝.
最后,送上投票頁面的截圖,處理過的,僅供欣賞,呵呵



浙公網安備 33010602011771號