从 PHP 服务器获取图像到 Android

发布于 2024-11-07 20:15:30 字数 654 浏览 0 评论 0原文

我正在制作一个 Android 应用程序原型,需要将图像从 Web 服务器获取到 Android ListView。我通过这个线程了解Android方面的事情(尽管尚未实现和测试)ListView 中图像的延迟加载

我需要 PHP/服务器端的帮助。需要在列表视图中填充的特定图像将动态决定(那些具有给定标签的图像)。我是 Web 应用程序的新手,但已经成功设置了一个可以运行 PHP 脚本的 Web 服务器。

1) Android 决定检索哪些标签。建立 HTTP 连接并使用给定标签作为参数调用 PHP 脚本。

2) PHP 脚本在 MySQL 数据库中查找标签,确定要上传的图像的 ID,这些图像存储在文件夹中。

3)[这是我不清楚如何实现的地方] PHP 发送这些图像,然后发送与每个图像关联的元数据。发送的记录条数不会预先固定,而是由MySQL返回的记录条数决定(仅固定最大记录数)。

我将非常感谢任何示例脚本,以及指向我可以在哪里找到更多信息以更好地了解内部工作原理的指针。另外,如果有更好的框架来完成我想做的事情,我很高兴了解这一点(我没有与 PHP/MySQL 结婚)。

I am prototyping an android application and need to get images from a web server to Android ListView. I understand the android side of things (although am yet to implement and test) via this thread Lazy load of images in ListView

I need help with the PHP/server side of it. The particular images that need to be populated in a list view will be decided dynamically (those images that have a given tag). I am new to web applications but have managed to set up a web server which can run PHP scripts.

1) Android decides which tags to retrieve. Makes an HTTP connection and calls a PHP script with the given tag as a parameter.

2) The PHP script looks up the MySQL database for the tag, decides the ids of images to upload, which are stored in a folder.

3) [Here is where I am unclear how to implement] The PHP sends these images followed by meta-data associated with each image. The number of records to send will not be fixed beforehand and will be decided by the number of records returned by MySQL (only maximum will be fixed).

I would greatly appreciate any sample scripts, and pointers to where I could find more information to better understand the inner working. Also, if there are better frameworks to do what I want to, I am happy to learn about that (I am not married to PHP/MySQL).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

看春风乍起 2024-11-14 20:15:30

这是获取单个图像并在图像视图中显示的代码。

public class Database_demo extends Activity {

public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;

int[] flags;
String strImageName;
int n = 10000;
String[] mySecondStringArray = new String[n];
String[] strArray;

HashMap<String, String> hm;
List<HashMap<String, String>> aList;
InputStream is = null;
String result = "";
JSONObject jArray = null;
private String Qrimage;
private Bitmap bmp;

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

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(
                "http://192.168.1.50/XXXX/getimage.php");
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        jArray = new JSONObject(result);
        JSONArray json = jArray.getJSONArray("tablename");
        for (int i = 0; i < json.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject e = json.getJSONObject(i);
            Qrimage = e.getString("imagefieldname");
            System.out.println(Qrimage);

            byte[] qrimage = Base64.decode(Qrimage.getBytes(), i);

            System.out.println(qrimage);
            bmp = BitmapFactory.decodeByteArray(qrimage, 0, qrimage.length);
            ImageView imageview = (ImageView) findViewById(R.id.flag);

            imageview.setImageBitmap(bmp);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}
  }

PHP 文件

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="databasename"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");




$sql = "SELECT * FROM tablename"; 

$result1 = mysql_query($sql);

$json = array();

if(mysql_num_rows($result1)){
while($row=mysql_fetch_assoc($result1)){
$json['tablename'][]=$row;
}
}


mysql_close($con);
echo json_encode($json); 

?> 

This is the code to get the single image and displayed in image view.

public class Database_demo extends Activity {

public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;

int[] flags;
String strImageName;
int n = 10000;
String[] mySecondStringArray = new String[n];
String[] strArray;

HashMap<String, String> hm;
List<HashMap<String, String>> aList;
InputStream is = null;
String result = "";
JSONObject jArray = null;
private String Qrimage;
private Bitmap bmp;

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

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(
                "http://192.168.1.50/XXXX/getimage.php");
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        jArray = new JSONObject(result);
        JSONArray json = jArray.getJSONArray("tablename");
        for (int i = 0; i < json.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject e = json.getJSONObject(i);
            Qrimage = e.getString("imagefieldname");
            System.out.println(Qrimage);

            byte[] qrimage = Base64.decode(Qrimage.getBytes(), i);

            System.out.println(qrimage);
            bmp = BitmapFactory.decodeByteArray(qrimage, 0, qrimage.length);
            ImageView imageview = (ImageView) findViewById(R.id.flag);

            imageview.setImageBitmap(bmp);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}
  }

Php file

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="databasename"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");




$sql = "SELECT * FROM tablename"; 

$result1 = mysql_query($sql);

$json = array();

if(mysql_num_rows($result1)){
while($row=mysql_fetch_assoc($result1)){
$json['tablename'][]=$row;
}
}


mysql_close($con);
echo json_encode($json); 

?> 
不语却知心 2024-11-14 20:15:30

我想您应该使用 JSON 通过 HTTP 连接将数据发送到您的移动设备。对于低互联网连接,我不喜欢 SOAP。

如果您无法直接通过 HTTP URL 加载图像,您可以以 JSON 和 mime 类型发送图像数据,并通过图像数据创建图像对象。

I guess you should use JSON to send data to your mobile device via HTTP connection. For low internet connect I don't prefer SOAP.

If you can not load images directly via HTTP URL you can send image data in JSON, and mime type as well and create image object through image data.

单挑你×的.吻 2024-11-14 20:15:30

如果我是你,我会做一个 php webservice nosoap http://android- Developers.blogspot.com/2009/05/painless-threading.html

用于下载图像。 Api的我会使用kso​​ap2 下载

其余的阅读了很多,但实际上很简单:D

If i were you i would do a php webservice nosoap http://android-developers.blogspot.com/2009/05/painless-threading.html

for dowload images. Api's i would use ksoap2 dowload

the rest is reading a lot but actually it's easy :D

红衣飘飘貌似仙 2024-11-14 20:15:30

我使用了InputStream 和OutputStream,就像使用Java 下载文件一样。首先,我从 PHP/JSON 脚本获取文件名(在服务器上)。当然,这个方法可以优化,它可以清除缓存文件夹中的旧文件。

private static File getImage(String filename) {
    String localFilename = new File(filename).getName();

    File img = new File("/sdcard/app/tmp/" + localFilename);

    // Create directories
    new File("/sdcard/app/tmp/").mkdirs();

    // only download new images
    if (!img.exists()) {
        try {
            URL imageUrl = new URL("http://example.com/images/" + filename);
            InputStream in = imageUrl.openStream();
            OutputStream out = new BufferedOutputStream(new FileOutputStream(img));

            for (int b; (b = in.read()) != -1;) {
                out.write(b);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            img = null;
        } catch (IOException e) {
            img = null;
        }
    }
    return img;
}

I used an InputStream and OutputStream, just like you download files with Java. First I get the filename (on the server) from a PHP/JSON script. Off course this method could be optimized that it clears old files in the cache folder.

private static File getImage(String filename) {
    String localFilename = new File(filename).getName();

    File img = new File("/sdcard/app/tmp/" + localFilename);

    // Create directories
    new File("/sdcard/app/tmp/").mkdirs();

    // only download new images
    if (!img.exists()) {
        try {
            URL imageUrl = new URL("http://example.com/images/" + filename);
            InputStream in = imageUrl.openStream();
            OutputStream out = new BufferedOutputStream(new FileOutputStream(img));

            for (int b; (b = in.read()) != -1;) {
                out.write(b);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            img = null;
        } catch (IOException e) {
            img = null;
        }
    }
    return img;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文