Reading image file from filesystem

blov · · 664 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I have been trying to read an image file from the f/s after uploading it from a webpage and I am stuck.</p> <pre><code>func GetImage(path string) image.Image{ reader, _ := os.Open(path) defer reader.Close() im, _, err := image.Decode(reader) if err != nil { fmt.println(err) } return im } </code></pre> <p>Does anyone know where I am going wrong? This function seems to returns image data (I think []bytes) but nothing I can add to a HTML image tag. Thanks guys.</p> <hr/>**评论:**<br/><br/>lwe: <pre><p>If I get this right you want to return the image as a path so you can integrate into a img src element. Well. You got the start right. What you have to do now is is actually return the image so it might be displayed. You are probably using a library to return http responses right? So set the response header mime type to the appropriate image format. E.g. image/jpeg and return the byte data to the requesting client. You don&#39;t actually have to decode the image if you only want to return it. </p> <p>But you can probably find a full tutorial online somewhere. Look for some of the key words from my post. </p></pre>kadema: <pre><p>You are right about me using a library, I am thinking of using the vanilla http in the standard lib for serving this image. </p></pre>justinisrael: <pre><p>You say your goal is to return something that can be used within an html image tag. So you have two option from how I see it... </p> <p>1) If the original image path that you are reading is not within a filesystem location that can be served by the Web server, then you would have to copy it to another location and then return the path to that location so that it can be placed into the img tag. Then the web server would serve it normally as static data. </p> <p>2) Again if your source image can&#39;t be served directly from its location by the Web server, you could base64 encode it:</p> <p><a href="https://golang.org/pkg/encoding/base64/" rel="nofollow">https://golang.org/pkg/encoding/base64/</a></p> <p><a href="http://danielmclaren.com/node/90" rel="nofollow">http://danielmclaren.com/node/90</a></p></pre>kadema: <pre><p>I am thinking I should serve it as static data instead, which in retrospect seems like a better idea.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

664 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传