ラベル Flickr API の投稿を表示しています。 すべての投稿を表示
ラベル Flickr API の投稿を表示しています。 すべての投稿を表示

2016年11月19日土曜日

Android Flickr API 显示缩略图



两个后台任务,一个负责得到列表,另一个下载每一个图片。
保存缩略图到getApplication().getCacheDir(),如果文件存在就读Cache,
不存在时从网络下载。



/**
 * Created by E560 on 2016/11/19.
 */

public class Mlistview extends AppCompatActivity {
    private GridView gridView;
    private final String imgsize = "s";
    private final String test_url = "http://cdefgab.web.fc2.com/song.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mlistview);
        new getlistmap().execute(test_url);
    }

    protected class getlistmap extends AsyncTask<String, Integer, List<String>> {
        /*
        * 返回所以縮圖,最長邊為 100的URL;
         */
        @Override
        protected List<String> doInBackground(String... params) {
            GetJson getJson = new GetJson(params[0]);
            List<String> listurl = new ArrayList<String>();
            try {
                HashMap<Integer, HashMap> items_map = getJson.jsonMap();
                for (int i = 0; i < items_map.size(); i++) {
                    listurl.add(GetJson.img_url(items_map.get(i), imgsize));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return listurl;
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            super.onPostExecute(strings);
            gridView = (GridView) findViewById(R.id.mlistview);
            myAdapter my = new myAdapter(strings);
            my.notifyDataSetChanged();
            gridView.setAdapter(my);
        }
    }

    protected class myAdapter extends BaseAdapter {
        private List<String> list;

        public myAdapter(List<String> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
            View v = new View(getApplication());
            if (convertView == null) {
                v = LayoutInflater.from(getApplication()).inflate(R.layout.ladapter, null);
            } else {
                v = convertView;
            }
            ImageView iv = (ImageView) v.findViewById(R.id.imageView2);
            iv.setImageBitmap(bitmap);
            GG gg = new GG(iv);
            gg.execute(list.get(position));
            return v;
        }

        public class GG extends AsyncTask<String, Integer, Bitmap> {
            private Bitmap bitmap;
            private ImageView iv;

            public GG(ImageView iv) {
                this.iv = iv;
            }

            @Override
            protected Bitmap doInBackground(String... params) {
                try {
//                     https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg
                    String[] sa = params[0].split("/");
                    File file = new File(getApplication().getCacheDir(), sa[sa.length - 1]);
                    if (file.isFile()) {
                        FileInputStream fin = new FileInputStream(file);
                        bitmap = BitmapFactory.decodeStream(fin);
                        fin.close();
                    } else {
                        bitmap = GetJson.getBitmap(params[0]);
                        FileOutputStream fon = new FileOutputStream(file);
                        ByteArrayOutputStream bas = GetJson.getBAOS(params[0]);
                        fon.write(bas.toByteArray());
                        fon.flush();
                        fon.close();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                iv.setImageBitmap(bitmap);
            }
        }
    }
}




2016年11月16日水曜日

Android flickr 工具类

Android flickr 工具类

得到Json的 字节输入流,Byte数组输出流,JSON的字符串。
http://cdefgab.web.fc2.com/song.json  JSON文件样本。


package com.example.java.m1115a.Tools;

import android.content.Context;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by java on 2016/11/15.
 */

public class HttpTools {
    private String url_path;
    private Context context;

    public HttpTools(String url_path) {
        this.url_path = url_path;
    }

    public HttpTools(String url_path, Context context) {
        this.url_path = url_path;
        this.context = context;
    }

    public InputStream getnetInputStream() throws Exception {
        URL url = new URL(url_path);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(10000);
        httpURLConnection.setReadTimeout(10000);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("GET");

        InputStream inputStream = null;
        if (httpURLConnection.getResponseCode() == 200) {
            inputStream = httpURLConnection.getInputStream();
        }
        return inputStream;
    }

    public ByteArrayOutputStream getbyteArrayOutputStream() throws Exception {
        InputStream inputStream = getnetInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buff)) != -1) {
            byteArrayOutputStream.write(buff, 0, len);
        }
        inputStream.close();
        return byteArrayOutputStream;
    }

    public String getjsonString() throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = getbyteArrayOutputStream();
        return byteArrayOutputStream.toString();
    }
}


继承HttpTools类
得到JSON的数字HashMap,得到Item的图片URL,得到图片的Bitmap


package com.example.java.m1115a.Tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by java on 2016/11/15.
 */

public class GetJson extends HttpTools {
    public GetJson(String url_path) {
        super(url_path);
    }

    public HashMap<Integer, HashMap> jsonMap() throws Exception {
        String jsonString = getjsonString();
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject jsonObject1 = jsonObject.getJSONObject("photos");
        JSONArray jsonArray = jsonObject1.getJSONArray("photo");
        HashMap<Integer, HashMap> jMap = new HashMap<Integer, HashMap>();

        for (int i = 0; i < jsonArray.length(); i++) {
            HashMap<String, String> item = new HashMap<String, String>();
            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
            Iterator<String> iterator = jsonObject2.keys();
            while (iterator.hasNext()) {
                String temp = iterator.next();
                item.put(temp, jsonObject2.getString(temp));
            }
            jMap.put(i, item);
        }
        return jMap;
    }

    public static String img_url(HashMap<String, String> item_hashMap) throws Exception {
        /*
        *
        * https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
        * https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
        * https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
        *
        * String farmid = item_hashMap.get("farm");
        * String Serverid = item_hashMap.get("server");
        * String id = item_hashMap.get("id");
        * String secret = item_hashMap.get("secret");
        * String img_url = "https://farm" + farmid + ".staticflickr.com/" + Serverid + "/" + id + "_" + secret + ".jpg";
        * System.out.println(img_url);
        */

        HashMap<String, String> temp_map = item_hashMap;
        return "https://farm" + item_hashMap.get("farm") + ".staticflickr.com/" + item_hashMap.get("server") + "/" + item_hashMap.get("id") + "_" + item_hashMap.get("secret") + ".jpg";
    }

    public static Bitmap getBitmap(String img_url) throws Exception {
        URL url = new URL(img_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(10000);
        httpURLConnection.setReadTimeout(10000);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("GET");
        Bitmap bitmap = null;
        if (httpURLConnection.getResponseCode() == httpURLConnection.HTTP_OK) {
            InputStream inputStream = httpURLConnection.getInputStream();
            if (inputStream != null) {
                byte[] buf = new byte[1024];
                int len = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                while ((len = inputStream.read(buf)) != -1) {
                    byteArrayOutputStream.write(buf, 0, len);
                    byteArrayOutputStream.flush();
                }
                bitmap = BitmapFactory.decodeByteArray(byteArrayOutputStream.toByteArray(), 0, byteArrayOutputStream.size());
                inputStream.close();
                byteArrayOutputStream.close();
            }
        }
        return bitmap;
    }
}



完成的例子,测试
每按一次按键,更换下一张图片。
应该不需要每次后 New URL.







package com.example.java.m1115a;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.java.m1115a.Tools.GetJson;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            private int cont;

            @Override
            public void onClick(View v) {
                new img().execute("http://cdefgab.web.fc2.com/song.json", String.valueOf(cont));
                cont++;
            }
        });
    }

    public class img extends AsyncTask<String, Integer, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {

            GetJson json = new GetJson(params[0]);
            int cont = Integer.parseInt(params[1]);
            Bitmap bitmap = null;
            try {
                bitmap = GetJson.getBitmap(GetJson.img_url(json.jsonMap().get(cont)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap == null) {
                Toast.makeText(MainActivity.this, "noImg", Toast.LENGTH_SHORT).show();
            }
            ImageView iv = (ImageView) findViewById(R.id.imageView);
            iv.setImageBitmap(bitmap);
        }
    }
}



2016/11/18
也可以直接加载InputStream的方式
bitmap = BitmapFactory.decodeStream(HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG"));



2013年8月28日水曜日

Flickr ファイル検索、Javascript, 前回の続き、検索した結果の写真を表示するようにします

Flickr ファイル検索、Javascript, 前回の続き、検索した結果の写真を表示するようにします。

Google Chromeご利用ください。

2013年8月26日月曜日

Flickr ファイル検索、Javascript,


1.
     key=e2d7f5575339924addac8fd8a3584035
     を入れ替えが必要です。下記のリンクをご参考ください。
     http://www.flickr.com/services/api/explore/flickr.photos.search

2.
     WindowsXDomainRequest() responseText取得したデータの取り扱い
     は不明、要確認。



<html>
<meta>
</meta>
<body>

<form id="flickr">
<input type="text" value="写真" onblur="ffun(this)"/><p>キーワード入力</p><br>
</form>

<script type="text/javascript">
function ffun(val){
var key=val.value;
link(key);
}

function link(key){
key=encodeURIComponent(key);
var url1="http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e2d7f5575339924addac8fd8a3584035&text="+key+"&format=rest";

if(navigator.userAgent.indexOf('MSIE')>-1){
winxxml(url1);
}else{
xxxml(url1);
}
}

function winxxml(ulink){
var date;
alert(ulink);
date=new XDomainRequest();
date.open('GET',ulink);
date.send();
alert(date.responseText);
}

function xxxml(ulink){
var date;
date=new XMLHttpRequest();
date.open('get',ulink,true);
date.send(null);
date.onreadystatechange=function(){
var ll=date.responseXML.getElementsByTagName('photo');
for(var i=0;i<ll.length;i++){
var aa=ll[i].getAttribute('farm');
var bb=ll[i].getAttribute('server');
var cc=ll[i].getAttribute('id');
var dd=ll[i].getAttribute('secret');
imglink(aa,bb,cc,dd);
}
}
}

function imglink(a,b,c,d){
 document.write('<br>');
 document.write('http://farm'+a+'.staticflickr.com/'+b+'/'+c+'_'+d+'.jpg');
}
</script>
</body>
</html>

2013年8月25日日曜日

Flickr API イメージリンク作成ファンクション パーツ

Flickr API  イメージリンク作成ファンクション

例:http://farm4.staticflickr.com/3792/9590406164_68f81cd67e.jpg


<script type="text/javascript">
var x=imglink('4','3792','9590406164','68f81cd67e');

function imglink(a,b,c,d){
document.write('<br>');
document.write('http://farm'+a+'.staticflickr.com/'+b+'/'+c+'_'+d+'.jpg');
}

</script>

2013年8月16日金曜日

Flickr API を確認中

Flickr API  を確認中です、認証しないで、画像の検索ができます。


flickr.photos.search

<?php
//url http://www.flickr.com/services/api/explore/flickr.photos.search
//http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
//or
//http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
//or
//http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)

$test=new flickr('秋葉原');



class flickr{

public function flickr($key){
$url='http://api.flickr.com/services/rest/?';
$imglink='http://farm%s.staticflickr.com/%s/%s_%s_b.jpg';
$imglink='http://farm%s.staticflickr.com/%s/%s_%s.jpg';
$imgshow='<img src="%s" alt="%s" title="%s" />';
$para['method']='flickr.photos.search';
$para['api_key']='********************************';
$para['text']=urldecode($key);
$para['format']='rest';
$para['sort']='date-posted-desc';
ksort($para);
echo $paraurl=$url.http_build_query($para);
$xml=simplexml_load_file($paraurl);


foreach($xml->photos->photo as $key=>$val){
$t_id=$val->attributes()->id;
$t_owner=$val->attributes()->owner;
$t_secret=$val->attributes()->secret;
$t_server=$val->attributes()->server;
$t_farm=$val->attributes()->farm;
$t_title=$val->attributes()->title;
$t_ispublic=$val->attributes()->ispublic;
$t_isfriend=$val->attributes()->isfriend;
$t_isfamily=$val->attributes()->isfamily;

$t_imglink=sprintf($imglink,$t_farm,$t_server,$t_id,$t_secret);
echo sprintf($imgshow,$t_imglink,$t_title,$t_title);
echo '<br>';
echo '<br>';

}

}

public function pinfo($ihoto_id){



}



}


?>




結果(一部)
130815@ソフマップ 秋葉原本館

アイスカフェラテ+カレードーナツ@DONQ 秋葉原店

「Google 新型Nexus7 近日入荷 16GB¥34,800 32GB¥39,800」ジャングル 秋葉原3号店

「Sushi 世の中はお盆休み中ですネ! 元祖寿司は休まずガンバッテ営業してます。ぜひっ!おいしい寿司を食べてってネ!!」元祖寿司 秋葉原中央通り店

「HTC ONE Google Edition ¥79,800」ジャングル 秋葉原3号店

「お盆特価!! WD20EZRX BOX 低発熱・静音動作・省エネ更に容量単価の安さがポイントです 2TB ¥6,980」BUY MORE 秋葉原本店

『ロットに注意!! 初期ロット無くなり次第終了です Xeon E3-1225v3 3.2GHz 本来は4コア4スレッドですが初期ロット「SR14U」のみ4コア8スレッド!!なのですっっ!! ¥24,480』BUY MORE 秋葉原本店