GAE / Java:如何从给定的URL加载图像并获取图像的宽度和高度

时间:2012-07-01 09:25:32

标签: java image google-app-engine

我正在使用GAE [JAVA]进行一些图像处理。 GAE不允许将文件写入磁盘,所以我希望我的App允许输入一个URL,然后我想检查这个指定的URL是否代表一个图像,如果是,我想得到它的高度和宽度。

有没有人提供一些解决方案来告诉我如何实现这个?

2 个答案:

答案 0 :(得分:5)

您可以使用GAE Image API。解决问题的简单示例如下:

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        final InputStream inputStream = url.openStream();
        int read;
        while ((read = inputStream.read()) != -1) {
            baos.write(read);
        }

        final Image image = ImagesServiceFactory.makeImage(baos.toByteArray());

        resp.getWriter().println("image width: " + image.getWidth());
        resp.getWriter().println("image height: " + image.getHeight());
    } catch (final IOException e) {
        resp.getWriter().println("image doesn't exists!");
    } catch (final IllegalArgumentException e) {
        resp.getWriter().println("invalid image!");
    }

完成Servlet以执行此操作:

package foo.bar;

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

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesServiceFactory;

@SuppressWarnings("serial")
public class MyFirstWebAppServlet extends HttpServlet {
    @Override
    public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
        URL url;
        if ("exists".equals(req.getParameter("image"))) {
            url = new URL("https://www.google.com/logos/classicplus.png");
        } else if ("notImage".equals(req.getParameter("image"))) {
            url = new URL("http://www.google.com");
        } else {
            url = new URL("http://foo.bar/image.png");
        }

        resp.setContentType("text/plain");
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            final InputStream inputStream = url.openStream();
            int read;
            while ((read = inputStream.read()) != -1) {
                baos.write(read);
            }

            final Image image = ImagesServiceFactory.makeImage(baos.toByteArray());

            resp.getWriter().println("image width: " + image.getWidth());
            resp.getWriter().println("image height: " + image.getHeight());
        } catch (final IOException e) {
            resp.getWriter().println("image doesn't exists!");
        } catch (final IllegalArgumentException e) {
            resp.getWriter().println("invalid image!");
        }

    }
}

答案 1 :(得分:-2)

也许这种方式很奇怪,但我认为你可以使用javascript

var img=new Image();
img.src="http://www.google.com.hk/images/nav_logo107.png";
img.height;
img.width;

enter image description here

如果图像没有退出,则会抛出404(未找到)问题。