473,769 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

urllib and saving pictures? [solved]

2 New Member
Hi.

This is my first post, and is about an assignment I've at my college.

An overall description:
We have to make a function, with one argument, the URL. then we have to search the HTML code for any pictures, and to do that I will search for <img and src tags.

All that I can, but then we have to save the pictures local on my harddrive, and make a collage with all the pictures in it. My hindrance right now is the saving part.

For testing the script, I'm using this code:
Code:

Expand|Select|Wrap|Line Numbers
  1. def getImageUrl(urlstring):
  2.     import urllib
  3.     connection=urllib.urlopen(urlstring)
  4.     picture = connection.read()
  5.     connection.close()
  6.     curloc = picture.find("img")
  7.     if curloc <> -1:
  8.         picloc = picture.find("<src", curloc)
  9.         picstart = picture.rfind(">",0,picloc)
  10.         #writefile.open(picture,"wt")
  11.         pic = open(picture, 'wb').read
  12.         picture = urllib.urlopen(urlstring)
  13.         pic.write(picture)
  14.         pic.close()
  15.     else:
  16.         print "There is no pictures in this URL"

I know my code isn't optimized, but I just can't seem to find the function, so it will save my pictures...

In advanced thanks.
Greetings
Public2
Oct 30 '06 #1
4 6671
bartonc
6,596 Recognized Expert Expert
I'm in a rush at the moment and must be brief. For starters, this line is wrong:

Expand|Select|Wrap|Line Numbers
  1. pic = open(picture, 'wb').read
  2.  
probably should be
Expand|Select|Wrap|Line Numbers
  1. pic = open(picture, 'wb')
  2.  
Also, Your post didn't come through quite right. I reformatted. please check it.

More this afternoon
Oct 30 '06 #2
bartonc
6,596 Recognized Expert Expert
I don't see you getting the index of the last tag.
Once you have both the start and end indeces, get a slice of the block like this:
Expand|Select|Wrap|Line Numbers
  1. subBlock = block[start:end]
  2.  
Then go ahead and and write it
Oct 30 '06 #3
fuffens
38 New Member
The easiest way to retreive the image file is probably to use urlretrieve in the urllib module.

For example if you want to store the thescripts logo from this homepage on your local drive you can do the following:

Expand|Select|Wrap|Line Numbers
  1. import urllib
  2. urllib.urlretrieve(r'http://www.thescripts.com/images/logo.jpg', r'c:\temp\logo.jpg')
Good luck!
/Fredrik
Oct 31 '06 #4
public2
2 New Member
Hey again.

I finally got finished with my assignment, and thought I would write the code down here. It turned out that we had to make most of the code in Jython, so some of the modules couldn't be used, but I managed anyway. Here is the complete code:

Expand|Select|Wrap|Line Numbers
  1. import urllib
  2. from urlparse import urljoin
  3. import random
  4.  
  5. def makeCollageFromUrl(urlString):    
  6.     listOfImages = getImagesUrl(urlString)
  7.     imageNames = []
  8.     for imageUrl in listOfImages:
  9.         filename = saveImage(imageUrl)
  10.         imageNames.append(filename)
  11.     width = 640
  12.     height = 480
  13.     picture = makeEmptyPicture(width,height)
  14.     for imageName in imageNames:
  15.         p = makePicture(imageName)
  16.         if p.getWidth()<width and p.getHeight()<height:
  17.             copyPictureToPicture(p,picture,random.randint(0,width-p.getWidth()),random.randint(0,height-p.getHeight()),0.5)
  18.  
  19.     picture.show()
  20.     writePictureTo(picture,r"C:\HTMLCollage.jpg")
  21.  
  22. def getImagesUrl(urlString):
  23.   connection=urllib.urlopen(urlString)
  24.   getPictures = connection.read()
  25.   connection.close()
  26.   executeIndex = 0
  27.   PicHTMLlist = []
  28.   while getPictures.find("<img",executeIndex) <> -1:
  29.     currentPicIndex = getPictures.find("<img",executeIndex)
  30.     currentSrcIndex = getPictures.find("src=",currentPicIndex)
  31.     nxtIndex = getPictures.find(">",currentSrcIndex)
  32.     executeIndex = nxtIndex
  33.     if getPictures.find("http",currentSrcIndex,nxtIndex)!=-1:
  34.         end = getPictures.find(" ",currentSrcIndex,nxtIndex)
  35.         currentPic = getPictures[currentSrcIndex+4:end]
  36.         currentPic = currentPic.replace('"'," ")
  37.         currentPic = currentPic.replace("'"," ")
  38.         repCurrPic = currentPic.lstrip()
  39.         repCurrPic = repCurrPic.rstrip()
  40.         if repCurrPic.rfind(".jpg") != -1 or repCurrPic.rfind(".gif") != -1:
  41.             PicHTMLlist.append(repCurrPic)
  42.   return PicHTMLlist
  43.  
  44. def saveImage(urlString):
  45.     connection = urllib.urlopen(urlString)
  46.     getPictures = connection.read()
  47.     connection.close()
  48.     sepIndex = urlString.rfind("/")
  49.     filnavn = urlString[(sepIndex+1):]
  50.     file = open(filnavn,"wb")
  51.     file.write(getPictures)
  52.     file.close()
  53.     return filnavn
  54.  
  55. def copyPictureToPicture(sourcePic,targetPic,offsetX,offsetY, blend):
  56.   for x in range(1,sourcePic.getWidth()+1):
  57.     for y in range(1,sourcePic.getHeight()+1):
  58.       color = sourcePic.getPixel(x,y).getColor()
  59.       targetPixel = targetPic.getPixel(x+offsetX,y+offsetY)
  60.       targetColor = targetPixel.getColor()
  61.       targetPixel.setRed(int(color.getRed()*blend+targetColor.getRed()*blend))
  62.       targetPixel.setGreen(int(color.getGreen()*blend+targetColor.getGreen()*blend))
  63.       targetPixel.setBlue(int(color.getBlue()*blend+targetColor.getBlue()*blend))
  64.  
There might be some word in Danish, but most of it is in English. Thanks for your help.

Have a great evening.

Greetings Public2
Oct 31 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2460
by: Haim Ashkenazi | last post by:
Hi I'm writing a script that uses urllib on win98. until now I used python 2.3.x (x < 4) and it worked ok. I re-installed windows and installed python 2.3.4 and now I get an error when trying to open a url "no host given": Python 2.3.4 (#53, May 25 2004, 21:17:02) on win32 Type "copyright", "credits" or "license()" for more information.
11
5058
by: Pater Maximus | last post by:
I am trying to implement the recipe listed at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/211886 However, I can not get to first base. When I try to run import urllib fo=urllib.urlopen("http://www.dictionary.com/") page = fo.read() I get:
0
3597
by: Pieter Edelman | last post by:
Hi all, I'm trying to submit some data using a POST request to a HTTP server with BASIC authentication with python, but I can't get it to work. Since it's driving me completely nuts, so here's my cry for help. The server is an elog logbook server (http://midas.psi.ch/elog/). It is protected with a password and an empty username. I can login both using urllib and urllib2 (suppose the password is "foobar", the logbook is running on port...
1
2074
by: Timothy Wu | last post by:
Hi, I'm trying to fill the form on page http://www.cbs.dtu.dk/services/TMHMM/ using urllib. There are two peculiarities. First of all, I am filling in incorrect key/value pairs in the parameters on purpose because that's the only way I can get it to work.. For "version" I am suppose to leave it unchecked, having value of empty string. And for name "outform" I am suppose to assign it a value of "-short". Instead, I left out
0
2906
by: Mattias | last post by:
I'm saving pictures on my harddrive from our webcam with GetResponseStream() .. Everything works fine, but after approximately 1h identical images are being saved. I checked the webpage but those pictures are still being refreshed. Code snippet: req = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(fullpath); req.Credentials = System.Net.CredentialCache.DefaultCredentials; // Return request in a response stream res =...
1
2010
by: adolph | last post by:
Using Access2000, I would like to resize an image then save it to a new file with the resized size. I'm taking pictures (JPGs) with my digitial set at 3.2 megs. I've figured out how to get my access program to find the pictures and show them as thumbnails so I can add a description and notes. I then rename and save these pictures to a different location and add a record to a table with the new file name and location. But the picture...
2
3764
by: Peder Y | last post by:
My code is something like this: --------------- Image img = Image.FromFile("somefile.bmp"); FileStream fStream = new FileStream("someBinaryFile.dat"); BinaryWriter bw = new BinaryWriter(fStream); img.Save(bw.BaseStream, ImageFormat.Bmp);
4
1674
by: junkdump2861 | last post by:
Here's the problem: using Netscape 7.1, I type use the view page source command (url is http://en.wikipedia.org/wiki/Cain) and save the raw HTML file and it's 67 kb, and has the addresses of all the images in it. I want the exact same thing from my Python script, but I'm not getting it. Instead, I get a file only 21 kb that has no image addresses. Here's the code I use: import urllib f =...
0
1110
by: linksterman | last post by:
i was wondering if there was anyway to load an image into a local variable using urllib or urllib2. i am currently using urllib.urlretrieve method of this, but it has to save each picture before i can use it. so i was wondering if there was any way for me to directly use pictures from the web.
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.