導航:首頁 > 操作系統 > androidurl獲取圖片大小

androidurl獲取圖片大小

發布時間:2022-06-17 00:47:42

android 如何獲得網路文件大小

public long getFileSize(String urlString) throws IOException,Exception{
long lenght = 0;
String url = UrlEncode(urlString, "UTF-8");
//URL mUrl = new URL(urlString);
URL mUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
conn .setRequestProperty("Accept-Encoding", "identity");
conn.setRequestProperty("Referer", url);
//conn.setRequestProperty("Referer", urlString);
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();

int responseCode = conn.getResponseCode();
// 判斷請求是否成功處理
if (responseCode == HttpStatus.SC_OK) {
lenght = conn.getContentLength();
}

return lenght;
}

② Android如何獲取網路圖片

android中獲取網路圖片是一件耗時的操作,如果直接獲取有可能會出現應用程序無響應(ANR:Application Not Responding)對話框的情況。對於這種情況,一般的方法就是耗時操作用線程來實現。下面列三種獲取url圖片的方法:


  1. 直接獲取:(容易:ANR,不建議)

java">mImageView=(ImageView)this.findViewById(R.id.imageThreadConcept);
Drawabledrawable=loadImageFromNetwork(IMAGE_URL);
mImageView.setImageDrawable(drawable);

2. 後台線程獲取url圖片:

mImageView=(ImageView)this.findViewById(R.id.imageThreadConcept);
newThread(newRunnable(){
Drawabledrawable=loadImageFromNetwork(IMAGE_URL);
@Override
publicvoidrun(){

//post()特別關鍵,就是到UI主線程去更新圖片
mImageView.post(newRunnable(){
@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
mImageView.setImageDrawable(drawable);
}});
}

}).start();

3.AsyncTask獲取url圖片

mImageView=(ImageView)this.findViewById(R.id.imageThreadConcept);
newDownloadImageTask().execute(IMAGE_URL);
<String,Void,Drawable>
{

(String...urls){
returnloadImageFromNetwork(urls[0]);
}
protectedvoidonPostExecute(Drawableresult){
mImageView.setImageDrawable(result);
}
}

③ android怎麼從sd卡指定的文件夾中獲取所有圖片的路徑URL,謝謝~感謝各位大神了

直接調用文件管理器選擇圖片即可。
1、調用系統提供的圖片選擇器,代碼如下:
//注意,在Android4.4系統下建議使用 Intent.ACTION_OPEN_DOCUMENT方式
if (Utility.isKK()) {

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {

Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column

};
處理返回結果:
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PIC_RESULT://選擇圖庫
case PIC_RESULT_KK:
imageFileUri = intent.getData();//獲取選擇圖片的URI
break;


2、除此自外,系統還提供一種選擇器,這個圖片選擇器可以屏蔽掉那個auto backup的目錄.所以就開始打算用這個圖片選擇器來選圖片了.
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){
startActivityForResult(intent, SELECT_PIC_KITKAT);
}else{
startActivityForResult(intent, SELECT_PIC);
}
為什麼要分開不同版本呢?其實在4.3或以下可以直接用ACTION_GET_CONTENT的,在4.4或以上,官方建議用ACTION_OPEN_DOCUMENT,主要區別是他們返回的Uri.4.3返回的是帶文件路徑的,而4.4返回的卻是content://com.android.providers.media.documents/document/image:3951這樣的,沒有路徑,只有圖片編號的uri.可以通過以下方式,處理URI。
參考:Android 4.4從圖庫選擇圖片,獲取圖片路徑並裁剪
public static String getPath(final Context context, final Uri uri) {

final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];

if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}

// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {

final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];

Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}

final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};

return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {

// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();

return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}

return null;
}

public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {

Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};

try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}

public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

3、使用其它開源組件如PhotoView。

④ android中怎麼跳轉到相冊獲取照片並得到url

方法/步驟
1
如下圖所示,需要根據URL地址獲取圖片載入到圖中Anroid機器人所在的位置,這是運行前的效果:

2
首先需根據URL地址獲取圖片,如下所示,urladdr即為圖片地址,返回Drawable對象:
//download image from network using @urladdress
private Drawable loadImageFromNetwork(String urladdr) {
// TODO Auto-generated method stub
Drawable drawable = null;
try{
//judge if has picture locate or not according to filename
drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
}catch(IOException e){
Log.d("test",e.getMessage());
}
if(drawable == null){
Log.d("test","null drawable");
}else{
Log.d("test","not null drawable");
}
return drawable;
}
3
獲取到圖片後,需要更新主線程UI資源,考慮到時間以及界面反應延遲等,所以採用線程加以處理,如下圖所示:
// image
new Thread(new Runnable(){
Drawable drawable = loadImageFromNetwork(urladdress);
@Override
public void run(){
//post() is quite important,update pictures in UI main thread
image.post(new Runnable(){
@Override
public void run(){
//TODO Auto-generated method stub
image.setImageDrawable(drawable);
}
});
}

//download image from network using @urladdress
private Drawable loadImageFromNetwork(String urladdr) {
//... 略(如 1 中所示)
}
}).start(); //線程啟動
4
說明:在上述示例代碼中,image是ImageView類的一個對象,也就是APP中的一個顯示圖像組件,利用獲取到的圖片drawable去更新image,運行效果如下所示:

⑤ android根據url獲取網路圖片報錯

這個看著是https協議的URL,用普通的http請求就報錯了,我這里只有請求https到流的代碼,給你先看看,把流再轉成文件 就可以了


@SuppressLint("ParserError")
(StringdownUrl,StringpostStr)throwsIOException{
Stringres="";

HttpsURLConnection.setDefaultHostnameVerifier(newNullHostNameVerifier());
SSLContextcontext=null;
try{
context=SSLContext.getInstance("TLS");
}catch(NoSuchAlgorithmExceptione1){
//TODOAuto-generatedcatchblock
e1.printStackTrace();
}

try{
context.init(null,newX509TrustManager[]{newmyX509TrustManager()},newSecureRandom());
}catch(KeyManagementExceptione1){
//TODOAuto-generatedcatchblock
e1.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

URLdUrl=newURL(downUrl);
HttpsURLConnectiondConn=(HttpsURLConnection)dUrl.openConnection();

dConn.setDoInput(true);
if(postStr!=""){
dConn.setDoOutput(true);
dConn.setRequestMethod("POST");
}

dConn.connect();

if(postStr!=""){
try{
BufferedWriterout=newBufferedWriter(newOutputStreamWriter(
dConn.getOutputStream()));
out.write(postStr);
out.flush();

}catch(Exceptione){
StringerrMsg=e.getMessage();
if(null!=errMsg){
Toasttoast=Toast.makeText(null,errMsg,Toast.LENGTH_LONG);
toast.show();
}

e.printStackTrace();
}

}


BufferedInputStreamin=newBufferedInputStream(dConn.getInputStream());

returnin;
}


{
@Override
publicbooleanverify(Stringhostname,SSLSessionsession){
//Log.i("RestUtilImpl","Approvingcertificatefor"+hostname);
returntrue;
}
}

{
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnull;
}

@Override
publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)
throwsCertificateException{
//TODOAuto-generatedmethodstub
}

@Override
publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)
throwsCertificateException{
//TODOAuto-generatedmethodstub
}
}

⑥ android通過HttpClient在網頁中讀取圖片,保存到手機裡面

通過url獲取圖片流,將流轉換成bitmap再將bitmap存放到手機

InputStreambitmapIs=HttpUtils.getStreamFromURL(imageURL);

Bitmapbitmap=BitmapFactory.decodeStream(bitmapIs);

Stringpath="/mnt/sdcard/image/";//這個就是你存放的路徑了。

FilebitmapFile=newFile(path);

FileOutputStreamfos=null;

if(!bitmapFile.exists()){

try{

bitmapFile.createNewFile();

fos=newFileOutputStream(bitmapFile);

bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

if(fos!=null){

fos.close();

}

}catch(IOExceptione){

e.printStackTrace();

}

}

}

⑦ android 使用URL獲取本地的文件

public String getFromAssets(String fileName){
try {
InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
BufferedReader bufReader = new BufferedReader(inputReader);
String line="";
String Result="";
while((line = bufReader.readLine()) != null)
Result += line;
return Result;
} catch (Exception e) {
e.printStackTrace();
}
}

⑧ android大圖片處理問題

也不知道樓主解決了沒有,解決辦法是什麼。我顯示圖片時,是縮小後再顯示(相當於顯示縮略圖),不改變原圖文件大小。但我需要對圖片做順時針旋轉(90度角轉一次),並保存旋轉後的圖片(旋轉功能已實現)。問題來了:似乎要進行旋轉處理,必須得先把圖讀到內存(Bitmap),這樣的話,壓縮讀取後旋轉,圖片失真;原圖不壓縮讀到內存,又可能內存溢出,也不知道怎麼辦。看系統自帶的3D相冊,圖片的「向左旋轉」、「向右旋轉」的功能挺好,貌似不會改變圖片質量,不知道怎麼實現的。

⑨ Android載入網路圖片,能自動生成縮略圖嗎

不能自動載入縮略圖。
一般的處理邏輯是你的伺服器要支持圖片處理,比如你在url後面跟一個想要的圖片尺寸(100x100),伺服器就能返回一個處理後尺寸接近100x100的圖片給你。

⑩ android中如何在下載前獲取下載文件大小

得到文件url,再conn.getContentLength()就可以了

閱讀全文

與androidurl獲取圖片大小相關的資料

熱點內容
windows如何代碼bat啟動伺服器 瀏覽:454
軟體太卡與伺服器有什麼關系 瀏覽:402
給心理治療師pdf 瀏覽:218
robinhood加密交易條件 瀏覽:310
衛生間解壓方法 瀏覽:450
u盤如何做加密文件放照片 瀏覽:327
文件夾自己加了exe 瀏覽:257
小豬cms直播系統源碼 瀏覽:878
山東廣電雲伺服器 瀏覽:354
javadate與mysqldate 瀏覽:244
javalong比較 瀏覽:9
加密大師看不見加密文件 瀏覽:307
想做一個業余程序員 瀏覽:793
python選出行 瀏覽:249
cat命令windows 瀏覽:910
python算術游戲 瀏覽:532
常微分方程第二版pdf 瀏覽:23
phpJava學多久 瀏覽:722
php博客畢業設計 瀏覽:796
資料庫編程pdf 瀏覽:905