您好,登錄后才能下訂單哦!
Android應(yīng)用中怎么實(shí)現(xiàn)利用圖片路徑查看圖片?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
1.在項(xiàng)目清單中添加網(wǎng)絡(luò)訪問權(quán)限
<!--訪問網(wǎng)絡(luò)的權(quán)限--> <uses-permission android:name="android.permission.INTERNET"/>
2.獲取網(wǎng)絡(luò)圖片數(shù)據(jù)
/** * 獲取網(wǎng)絡(luò)圖片的數(shù)據(jù) * @param path 網(wǎng)絡(luò)圖片路徑 * @return * @throws Exception */ public static byte[] getImage(String path) throws Exception { URL url=new URL(path); HttpURLConnection conn=(HttpURLConnection)url.openConnection();//得到基于HTTP協(xié)議的連接對象 conn.setConnectTimeout(5000);//設(shè)置超時時間 conn.setRequestMethod("GET");//請求方式 if(conn.getResponseCode()==200){//判斷是否請求成功 InputStream inputStream=conn.getInputStream(); return read(inputStream); } return null; } /** * 讀取流中的數(shù)據(jù) */ public static byte[] read(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); byte[] b=new byte[1024]; int len=0; while((len=inputStream.read(b))!=-1){ outputStream.write(b); } inputStream.close(); return outputStream.toByteArray(); }
3.處理查看圖片的控制
public class NetimageActivity extends Activity { private EditText pathText; private ImageView imageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); pathText=(EditText)this.findViewById(R.id.imagepath);//圖片路徑 imageView=(ImageView)this.findViewById(R.id.imageView);//顯示圖片控件 Button button=(Button)this.findViewById(R.id.button);//查看圖片按鈕 button.setOnClickListener(new ButtonClickListener());//注冊查看圖片按鈕事件 } /** * 處理查看圖片按鈕事件 */ private final class ButtonClickListener implements View.OnClickListener{ @Override public void onClick(View v) { //取得圖片路徑 String path=pathText.getText().toString(); try { //獲取圖片數(shù)據(jù) byte[] data=ImageService.getImage(path); //使用數(shù)組的所有數(shù)據(jù)構(gòu)建位圖對象 Bitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length); imageView.setImageBitmap(bitmap);//顯示圖片 } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), R.string.error, 1).show(); } } } }
關(guān)于Android應(yīng)用中怎么實(shí)現(xiàn)利用圖片路徑查看圖片問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。