不显示图像毕加索 [英] Picasso image not displaying

查看:223
本文介绍了不显示图像毕加索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个图像显示在我的应用程序,另一种是不,从浏览器但两者都可以访问。

这一个在我的免费主机不显示在我的应用程序。请没有,我可以从自由主机服务器看到的图像:

  http://www.justedhak.comlu.com/images/uploaded_images.jpg

这个人是从随机网站及其展示的应用程序。

  http://api.androidhive.info/json/movies/1.jpg

我的问题,是它可​​能的方式问题,我上传的形象呢?或可能是免费的主机(000webhost的)?请给我你的意见

我上传图像到服务器,然后在活动中展示我可以看到网址但其在应用程序没有显示。不过,我还添加了另一幅图像的URL和显示的应用程序。

这是得到的code网址图片

 保护无效showList(){
    尝试{
        JSONObject的jsonObj =新的JSONObject(myJSON);
        人民= jsonObj.getJSONArray(TAG_RESULTS);        的for(int i = 0; I< peoples.length();我++){
            JSONObject的C = peoples.getJSONObject(I)
            字符串ID = c.getString(TAG_ID);
            字符串URL = c.getString(TAG_PATH);
            Listitem.add(新列表项(ID,URL));
        }        GridViewAdapter适配器=新GridViewAdapter(这一点,R.layout.grid_item_layout,列表项);
     // gridView.setAdapter(gridAdapter);       list.setAdapter(适配器);    }赶上(JSONException E){
        e.printStackTrace();
    }}
公共类GetDataJSON扩展的AsyncTask<弦乐,太虚,字符串> {
     @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            DefaultHttpClient的HttpClient =新DefaultHttpClient(新BasicHttpParams());
            HttpPost httppost =新HttpPost(http://justedhak.comlu.com/get-data.php);            //取决于你的Web服务
            httppost.setHeader(内容类型,应用/ JSON);            为InputStream的InputStream = NULL;
            字符串结果= NULL;
            尝试{
                HTT presponse响应= httpclient.execute(httppost);
                HttpEntity实体= response.getEntity();                的InputStream = entity.getContent();
                // JSON默认为UTF-8
                读者的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中,UTF-8),8);
                StringBuilder的SB =新的StringBuilder();                串线= NULL;
                而((行= reader.readLine())!= NULL)
                {
                    sb.append(行+\\ n);
                }
                结果= sb.toString();
            }赶上(例外五){
                //哎呀
            }
            最后{
                尝试{如果(InputStream的!= NULL)inputStream.close();}赶上(例外挤){}
            }
            返回结果;
        }

这是上传图片

 }
公共无效的onclick(查看视图)
{
    Toast.makeText(AddImage.this上传图片,Toast.LENGTH_LONG).show();
    上传();      意图I =新意图(这一点,
                MainActivity.class);
      startActivity(ⅰ);
}
公共无效上传()
{
      日历thisCal = Calendar.getInstance();
      thisCal.getTimeInMillis();      // android.util.Log.i(时代班,+ thisCal在millisecinds时间值);   //位图位图= BitmapFactory.de codeResource(getResources(),R.drawable.ic_launcher);
 // ByteArrayOutputStream流=新ByteArrayOutputStream();
   // bmp.com preSS(Bitmap.Com pressFormat.PNG,90,流); // COM preSS你想要的格式。        意向意图= getIntent();
        串selectedImage = intent.getStringExtra(的ImagePath);
        乌里了fileURI = Uri.parse(selectedImage);   //乌里selectedImage = intent.getData();
    的System.out.println(fileURI所);
    的InputStream的ImageStream = NULL;
    尝试{
        的ImageStream = getContentResolver()openInputStream(fileURI所)。
    }赶上(FileNotFoundException异常五){
        e.printStackTrace();
    }    BMP位图= BitmapFactory.de codeStream(的ImageStream);    ByteArrayOutputStream流=新ByteArrayOutputStream();
    bmp.com preSS(Bitmap.Com pressFormat.JPEG,30,流);
    字节[]的字节数组= stream.toByteArray();
    位图位图= BitmapFactory.de codeByteArray的(字节数组,0,byteArray.length);
    imageview.setImageBitmap(位图);
    INT宽度= bitmap.getWidth();
    INT高度= bitmap.getHeight();
    的System.out.println(宽);
    的System.out.println(高度);
    getResizedBitmap(位图,200);
    尝试{
        stream.close();
        流= NULL;
    }赶上(IOException异常五){        e.printStackTrace();
    }    字符串image_str = Base64.en codeBytes(字节阵列);
    最终的ArrayList<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
    nameValuePairs.add(新BasicNameValuePair(形象,image_str));
    nameValuePairs.add(新BasicNameValuePair(标题,字幕));
    nameValuePairs.add(新BasicNameValuePair(名,乙脑));
    nameValuePairs.add(新BasicNameValuePair(categoriecategorie));
     线程t =新主题(新的Runnable(){    @覆盖
    公共无效的run(){
          尝试{                 HttpClient的HttpClient的=新DefaultHttpClient();
                 HttpPost httppost =新HttpPost(http://justedhak.comlu.com/images/upload_image.php);
                 httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                 HTT presponse响应= httpclient.execute(httppost);
                 最后弦乐the_string_response = convertResponseToString(响应);
                 runOnUiThread(新的Runnable(){                        @覆盖
                        公共无效的run(){
                            Toast.makeText(AddImage.this,响应+ the_string_response,Toast.LENGTH_LONG).show();
                        }
                    });             }赶上(最终例外五){
                  runOnUiThread(新的Runnable(){                    @覆盖
                    公共无效的run(){
                        Toast.makeText(AddImage.this,ERROR+ e.getMessage(),Toast.LENGTH_LONG).show();
                    }
                });
                   的System.out.println(错误的HTTP连接+ e.toString());
             }
    }
});
 t.start();
}

php文件

  $ CON = mysqli_connect($主机,$的uname,$ PWD,$分贝);$描述= $ _GET ['说明'];
$ categorie = $ _GET ['categorie'];
$图片网址=www.justedhak.comlu.com/images/uploaded_images.jpg;
$图像= $ _ POST ['形象'];     $二进制= base64_de code($图像);
    标题(内容类型:位图;字符集= utf-8');
    $文件=的fopen('uploaded_images.jpg','WB);
    FWRITE($文件,$二进制);
    FCLOSE($文件);$的SQL =插入图像(描述,categorie,路径)VALUES('$ categorie,$说明,$图片网址');
 如果(mysqli_query($ CON,$ sql中)){
  回声成功;
}
其他{
回声失败;
  }
mysqli_close($ CON);    回声图片上传完成!,请检查你的PHP文件目录......';


更新:

我已经找到了主要原因毕加索不显示您的图片是图片网址你JSON不与 http开头://

这是我的工作示例code(仅适用于获取图片网址和毕加索(Picasso)显示,不包括图片上传)

 公共类MainActivity扩展AppCompatActivity {    私人最终上下文mContext =这一点;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        最终的TextView的TextView =(的TextView)findViewById(R.id.textView);
        最后ImageView的ImageView的=(ImageView的)findViewById(R.id.imageView);
        字符串URL =htt​​p://justedhak.comlu.com/get-data.php;
        请求队列队列= Volley.newRequestQueue(mContext);
        JsonObjectRequest jsonObjectRequest =新JsonObjectRequest(Request.Method.GET,网址,空,新Response.Listener<&JSONObject的GT;(){
            @覆盖
            公共无效onResponse(JSONObject的响应){
                如果(响应= NULL&放大器;!&安培;!response.isNull(结果)){
                    尝试{
                        JSONArray jsonArray = response.getJSONArray(结果);
                        如果(jsonArray =空&放大器;!&放大器; jsonArray.length()大于0){
                            //只得到一个用来测试显示图像元素
                            的JSONObject的JSONObject = jsonArray.getJSONObject(1);
                            如果(的JSONObject = NULL&放大器;!&安培;!jsonObject.isNull(路径)){
                                字符串的ImagePath = jsonObject.getString(路径);
                                如果(的ImagePath =空&放大器;!&放大器;!imagePath.isEmpty()){
                                    textView.setText(的ImagePath);
                                    Picasso.with(mContext).load(HTTP://+的ImagePath).into(ImageView的);
                                }
                            }
                        }
                    }赶上(JSONException E){
                        textView.setText(e.toString());
                        e.printStackTrace();
                    }
                }
            }
        },新Response.ErrorListener(){
            @覆盖
            公共无效onErrorResponse(VolleyError错误){
                textView.setText(error.toString());
            }
        });        queue.add(jsonObjectRequest);
    }
}

这是结果的截图(可以留意的TextView 的价值,而不的http:// preFIX)

BNK的屏幕截图

P / S:获取请求作品也(您可以通过访问检查 http://justedhak.comlu.com/get-data.php 简单地通过任何网络浏览器,如Chrome浏览器)

综上所述,你将有2个选择:


  • 选项1:的更新图片网址在服务器数据库中,以便所有的人都开始与的http://

  • 选项2:的检查您的Andr​​oid客户端code图片网址,如果不与启动HTTP:// ,必须添加这preFIX正如我在上面的示例code

更新的终止


我觉得你可以,而不是HttpPost的尝试使用HTTPGET获取图像的URL。我刚才尝试和得到下面的结果;

{\"result\":[{\"id\":\"1\",\"name\":null,\"path\":\"http://api.androidhive.info/json/movies/1.jpg\"},{\"id\":\"2\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"28\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"27\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"26\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"25\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"24\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"23\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"22\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"21\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"20\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"19\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"},{\"id\":\"18\",\"name\":null,\"path\":\"www.justedhak.comlu.com/images/uploaded_images.jpg\"}]}

此外,请尝试使用HttpURLConnection类,OkHttp ...而不是Apache的HttpClient的,因为它的德precation现在。

希望这有助于!

one image is displaying on my app and the other is not, however both can be accesses from the browser.

this one in my free host is not displaying on my app. Please not that I can see the image from the free host server :

   http://www.justedhak.comlu.com/images/uploaded_images.jpg

this one is from a random site and its showing on the app.

http://api.androidhive.info/json/movies/1.jpg

My question, is it could the problem in the way I am uploading the image ? or could be the free host (000webhost) ? please give me your opinion

I am uploading image to server then displaying in the activity I can see the url but its not showing in the app. however I also add another image url and its showing in the app.

this is the code of getting url image

protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String url = c.getString(TAG_PATH); 
            Listitem.add(new Listitem(id,url));
        }

        GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, Listitem);
     //   gridView.setAdapter(gridAdapter); 

       list.setAdapter(adapter);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}
public class GetDataJSON extends AsyncTask<String, Void, String>{
     @Override
        protected String doInBackground(String... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://justedhak.comlu.com/get-data.php");

            // Depends on your web service
            httppost.setHeader("Content-type", "application/json");

            InputStream inputStream = null;
            String result = null;
            try {
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (Exception e) {
                // Oops
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

this is uploading image

}
public void onclick(View view)
{
    Toast.makeText(AddImage.this, "Uploading Image", Toast.LENGTH_LONG).show();                         
    upload();

      Intent i = new Intent(this,
                MainActivity.class);
      startActivity(i);
}
public void upload()
{
      Calendar thisCal = Calendar.getInstance();
      thisCal.getTimeInMillis();

      //  android.util.Log.i("Time Class ", " Time value in millisecinds "+ thisCal);

   // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);  
 //   ByteArrayOutputStream stream = new ByteArrayOutputStream();
   // bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.

        Intent intent = getIntent();
        String selectedImage= intent.getStringExtra("imagePath");
        Uri fileUri = Uri.parse(selectedImage);

   // Uri selectedImage = intent.getData();
    System.out.println(fileUri);
    InputStream imageStream = null;
    try {
        imageStream = getContentResolver().openInputStream(fileUri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    Bitmap bmp = BitmapFactory.decodeStream(imageStream);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 30, stream);


    byte[] byteArray = stream.toByteArray();
    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    imageview.setImageBitmap(bitmap);
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    System.out.println(width);
    System.out.println(height);


    getResizedBitmap( bitmap, 200);
    try {
        stream.close();
        stream = null;
    } catch (IOException e) {

        e.printStackTrace();
    }

    String image_str = Base64.encodeBytes(byteArray);
    final ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image",image_str));
    nameValuePairs.add(new BasicNameValuePair("caption",caption));
    nameValuePairs.add(new BasicNameValuePair("name","je"));
    nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
     Thread t = new Thread(new Runnable() {

    @Override
    public void run() {
          try{

                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost("http://justedhak.comlu.com/images/upload_image.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost);
                 final String the_string_response = convertResponseToString(response);
                 runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(AddImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                         
                        }
                    });

             }catch(final Exception e){
                  runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(AddImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();                             
                    }
                });
                   System.out.println("Error in http connection "+e.toString());
             }  
    }
});
 t.start();
}

php file

$con = mysqli_connect($host,$uname,$pwd,$db);

$description= $_GET['description'];
$categorie= $_GET['categorie'];
$imageurl="www.justedhak.comlu.com/images/uploaded_images.jpg";
$image=$_POST['image'];



     $binary=base64_decode($image);
    header('Content-Type: bitmap; charset=utf-8');
    $file = fopen('uploaded_images.jpg', 'wb');
    fwrite($file, $binary);
    fclose($file);

$sql = "insert into image (description,categorie,path) values ('$categorie','$description','$imageurl')";
 if(mysqli_query($con,$sql)){
  echo 'success';
}
else{
echo 'failure';
  }
mysqli_close($con);

    echo 'Image upload complete!!, Please check your php file directory……';

解决方案

UPDATE:

I have found the main reason that Picasso does not display your image is the image Url in your JSON does not start with http://.

Here is my working sample code (only for getting the image Url and displaying by Picasso, not including image uploading)

public class MainActivity extends AppCompatActivity {

    private final Context mContext = this;

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

        final TextView textView = (TextView) findViewById(R.id.textView);
        final ImageView imageView = (ImageView) findViewById(R.id.imageView);
        String url = "http://justedhak.comlu.com/get-data.php";
        RequestQueue queue = Volley.newRequestQueue(mContext);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (response != null && !response.isNull("result")) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("result");
                        if (jsonArray != null && jsonArray.length() > 0) {
                            // get only one element for testing display image
                            JSONObject jsonObject = jsonArray.getJSONObject(1);
                            if (jsonObject != null && !jsonObject.isNull("path")) {
                                String imagePath = jsonObject.getString("path");
                                if (imagePath != null && !imagePath.isEmpty()) {
                                    textView.setText(imagePath);
                                    Picasso.with(mContext).load("http://" + imagePath).into(imageView);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        textView.setText(e.toString());
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText(error.toString());
            }
        });

        queue.add(jsonObjectRequest);            
    }
}

And here is the result screenshot (you can pay attention to the textView's value, without http:// prefix)

P/S: GET request works also (you can check by access the http://justedhak.comlu.com/get-data.php simply by any web browser such as Chrome)

To sum up, you will have 2 options:

  • Option 1: Update the image Urls in your server database so that all of them start with http://
  • Option 2: Check the image Urls in your android client code, if not started with http://, must add this prefix as in my above sample code

END OF UPDATE


I think you can try using HttpGet instead of HttpPost for getting the image Urls. I have just tried and get the following results;

{"result":[{"id":"1","name":null,"path":"http://api.androidhive.info/json/movies/1.jpg"},{"id":"2","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"28","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"27","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"26","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"25","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"24","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"23","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"22","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"21","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"20","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"19","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"18","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"}]}

Moreover, try using HttpUrlConnection, OkHttp... instead of Apache HttpClient because of its deprecation now.

Hope this helps!

这篇关于不显示图像毕加索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆